Python:如何从成员函数中调用构造函数 [英] Python: How to call the constructor from within member function
问题描述
此问题/解答(成员函数中的Python调用构造函数)说,可以从在成员函数中.
This Question / Answer (Python call constructor in a member function) says it is possible to to call the constructor from within a member function.
我该怎么做?
这是一种好风格吗?
我用以下代码尝试过:
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
自从我调用了 build_new()
方法以来, inst.field
是否应该为 True
?
Since I called the build_new()
method inst.field
should be True
or not?
推荐答案
我相信您正在寻找的只是再次调用 init 函数.
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)
这将导致字段变量设置为True而不是False.基本上,您是在重新初始化实例,而不是创建一个全新的实例.
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.
您当前的代码创建一个新实例,并且在超出范围(即函数返回)时丢失对它的引用,因为您只是将self的名称重新绑定到一个不同的值,而实际上并没有改变self的内部内容
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.
这篇关于Python:如何从成员函数中调用构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!