Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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
like image 925
ivan Avatar asked Feb 11 '13 15:02

ivan


People also ask

Can I call method from Init Python?

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.

Can you call __ init __ again?

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!-)

Is __ init __ instance method?

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.)

Can I call a method inside a constructor in Python?

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.


2 Answers

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).

like image 80
ecatmur Avatar answered Sep 28 '22 18:09

ecatmur


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.

like image 43
mgilson Avatar answered Sep 28 '22 19:09

mgilson