【问题标题】:How to clear inner class attributes on parent creation如何在创建父级时清除内部类属性
【发布时间】:2018-05-02 13:50:33
【问题描述】:

我有一个嵌套类设置,例如下面的代码 sn-p。

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 = ""

调用父类时如何启动新的子类?

【问题讨论】:

  • 我不确定你想在这里完成什么,但类中的类通常是不好的做法
  • @bphi 如果他正在做一些元编程,这是有道理的。虽然这里似乎不是这样。

标签: python inner-classes


【解决方案1】:

不要把它作为一个内部类,而是作为一个单独的类,然后是一个即时属性:

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

【讨论】:

  • 希望每个类在自己内部“拥有”它的子类。但我猜这取决于反馈,因为它不是最佳解决方案。所以采用了我的代码来解决这个问题。
  • @RasmusEkman 你也可以在父类中移动类并调用self.child = self.child_class()。见编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-11-14
  • 2016-09-14
  • 1970-01-01
  • 2013-06-23
  • 1970-01-01
  • 1970-01-01
  • 2019-01-19
相关资源
最近更新 更多