I'm building an object that has an attribute whose value is randomly generated at instantiation. The attribute will be assigned a new value (also randomly) from time to time, so I'm defining a method to do so. Is it bad form to initialize the attribute by calling that method from within __init__
? It would be easy enough to avoid—I'd just have to duplicate a small amount of code—but it seems more elegant to call the method. Here's an example:
import random
class Robot(object):
def __init__(self):
self.setDirection()
def setDirection(self):
self.direction = random.random() * 360
You cannot call them explicitly. For instance, when you create a new object, Python automatically calls the __new__ method, which in turn calls the __init__ method.
3 Answers. Show activity on this post. It's fine to call __init__ more than once on an object, as long as __init__ is coded with the effect you want to obtain (whatever that may be). A typical case where it happens (so you'd better code __init__ appropriately!-)
As for your first question, __init__ is neither a staticmethod nor a classmethod; it is an ordinary instance method. (That is, it receives the instance as its first argument.)
Solution 1. A constructor can call methods, yes. A method can only call a constructor in the same way anything else can: by creating a new instance.
It's fine to call instance methods within __init__
, but be careful if they might be overridden in subclasses:
class A(object):
def __init__(self):
self.greet()
def greet(self):
print('Hello from A')
class B(A):
def __init__(self, name):
super(B, self).__init__()
self.name = name
def greet(self):
print('Hello from B', self.name)
Now if B is instantiated, B.greet
is called by A.__init__
before its preconditions are satisfied (self.name
is not defined).
There's nothing wrong with calling other instance methods within __init__
.
Note that in python there is a distinction between instance methods and class methods. I can't think of a good reason to use a class method within __init__
-- which isn't to say that a good reason doesn't exist, but that the cases are probably pretty rare.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With