Skip to content Skip to sidebar Skip to footer

Python: How To Call The Constructor From Within Member Function

This Question / Answer (Python call constructor in a member function) says it is possible to to call the constructor from within a member function. How do I do that? Is it good a s

Solution 1:

The problem is not in calling the constructor, but what you're doing with the result. self is just a local variable: assigning to it won't change anything at all about the current instance, it will just rebind the name to point to a new instance which is then discarded at the end of the method.

I'm not totally certain what you are trying to do, but perhaps you want a classmethod?

classSomeClass(object):
   ...
   @classmethoddefbuild_new(cls):
       return cls(True)



SomeClass.build_new(False)

Solution 2:

I believe what you are looking for is just calling the init function again.

classSomeClass(object):def__init__(self, field):
        self.field = field

    defbuild_new(self):
        self.__init__(True)

This will cause the field variable to be set to True over False. Basically, you are re-initializing the instance rather than creating a brand new one.

Your current code creates a new instance and just loses the reference to it when it goes out of scope (i.e. the function returning) because you are just rebinding the name of self to a different value not actually changing the inner contents of self.

Post a Comment for "Python: How To Call The Constructor From Within Member Function"