[英]How to update outer class attributes whenever inner class attributes change?
[英]How to clear inner class attributes on parent creation
我有一个嵌套的类设置,如下面的代码片段。
class test:
class child:
some_variable = None
当我尝试从另一个像波纹管的.py文件中调用此代码时
from testing import test
t = test()
t.child.some_variable ="123"
t = test()
print(t.child.some_variable)
我得到了输出
123
我希望得到无或至少出现错误消息。 我试图用以下方法解决它,但问题仍然存在,但输出相同。
class test:
def __init__(self):
self.child()
class child:
some_variable = None
def __init__(self):
self.some_variable = ""
呼叫父班时,如何启动新的子班?
通过不将其作为内部类,而将其作为单独的类,然后将其作为即时属性:
class child_class:
def __init__(self):
self.some_variable = None
class test:
def __init__(self):
self.child = child_class()
t = test()
t.child.some_variable = "123"
t = test()
print(t.child.some_variable) # prints None
或者,您可以有一个内部类,但仍然必须创建一个实例属性:
class test:
class child_class:
def __init__(self):
self.some_variable = None
def __init__(self):
self.child = self.child_class()
t = test()
t.child.some_variable = "123"
t = test()
print(t.child.some_variable) # also prints None
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.