1

I am trying to get new random name every time I call class. I am defining it as

def namemethod(): return ''.join(random.choice(string.lowercase) for x in range(5)) class Test(object): def __init__(self, name=namemethod()): self.name = name 

And I am calling Test class via for loop to get new name but I keep getting same name, isn't it suppose to call init method and get new random name?

for i in range(5): person = Test() print person.name 

Why person = Test() not calling namemethod everytime?

4

2 Answers 2

7

In this code:

class Test(object): def __init__(self, name=namemethod()): self.name = name 

The default argument

name=namemethod() 

only gets evaluated a single time for the entire class (default arguments always only get evaluated once)

What you probably want to do instead, is use name=None as default value for the name argument. The, in __init__(), you could do something like this:

class Test(object): def __init__(self, name=None): if name is None: name = namemethod() self.name = name 
Sign up to request clarification or add additional context in comments.

Comments

3

in your code, the name=namemethod() default argument is replaced permanently by a single instance returned by a call to namemethod

Your desired behaviour can be achieved using:

def namemethod(): return ''.join(random.choice(string.lowercase) for x in range(5)) class Test(object): def __init__(self, name=None): self.name = name if name is not None else namemethod() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.