简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM