[英]How to clear inner class attributes on parent creation
I have a nested class setup like the code snippet bellow. 我有一个嵌套的类设置,如下面的代码片段。
class test:
class child:
some_variable = None
When I try to call this code from another .py file like bellow 当我尝试从另一个像波纹管的.py文件中调用此代码时
from testing import test
t = test()
t.child.some_variable ="123"
t = test()
print(t.child.some_variable)
I get the output 我得到了输出
123
I expected to get None, or at least an error message. 我希望得到无或至少出现错误消息。 I have tried to solve it with the following approach but the problem persists with the same output. 我试图用以下方法解决它,但问题仍然存在,但输出相同。
class test:
def __init__(self):
self.child()
class child:
some_variable = None
def __init__(self):
self.some_variable = ""
How can I initiate a new child class when I am calling the parent class? 呼叫父班时,如何启动新的子班?
By don't having it as an inner class, but as a separate class and then an instant attribute: 通过不将其作为内部类,而将其作为单独的类,然后将其作为即时属性:
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
Or alternative you can have a inner class, but still you have to create an instance attribute: 或者,您可以有一个内部类,但仍然必须创建一个实例属性:
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.