簡體   English   中英

如何在父創建時清除內部類屬性

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM