Python: How to call the constructor from within member function

社会主义新天地 提交于 2020-12-10 08:56:06

问题


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 style?

I tried it with the following code:

class SomeClass(object):
    def __init__(self, field):
        self.field = field

    def build_new(self):
        self = SomeClass(True)

def main():
    inst = SomeClass(False)
    inst.build_new()
    print(inst.field)

if __name__ == '__main__':
    main()

As output I get: False

Since I called the build_new() method inst.field should be True or not?


回答1:


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

class SomeClass(object):
    def __init__(self, field):
        self.field = field

    def build_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.




回答2:


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?

class SomeClass(object):
   ...
   @classmethod
   def build_new(cls):
       return cls(True)



SomeClass.build_new(False)


来源:https://stackoverflow.com/questions/25118798/python-how-to-call-the-constructor-from-within-member-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!