Monday, 15 March 2010

python - Is it bad form to call an instance method from within that instance's __init__ method? -



python - Is it bad form to call an instance method from within that instance's __init__ method? -

i'm building object has attribute value randomly generated @ instantiation. attribute assigned new value (also randomly) time time, i'm defining method so. bad form initialize attribute calling method within __init__? easy plenty avoid—i'd have duplicate little amount of code—but seems more elegant phone call method. here's example:

import random class robot(object): def __init__(self): self.setdirection() def setdirection(self): self.direction = random.random() * 360

it's fine phone call instance methods within __init__, careful if might overridden in subclasses:

class a(object): def __init__(self): self.greet() def greet(self): print('hello a') class b(self): def __init__(self, name): super(b, self).__init__() self.name = name def greet(self): print('hello b', self.name)

in case b.greet called a.__init__ before preconditions satisfied (self.name not defined).

python methods initialization

No comments:

Post a Comment