简体   繁体   中英

Python Accessing to the parent class (Not inheritance)

Is possible access to the parent methods/properties in a class that are inside of the other class?

class ClassA:
    a = 'a'

    class ClassB():
        def method(self):
            return self.a

instance = ClassA()
instance2 = instance.ClassB()
instance2.method()

No, nesting a class doesn't automatically produce a relationship between instances. All you did was create an attribute on ClassA that happens to be a class object. Calling that attribute on instances just finds the class attribute and a new instance of ClassB is created without any knowledge of or reference to the ClassA instance.

You'll need to make such relationships explicit by passing in a reference:

class ClassB():
    def __init__(self, a):
        self.a = a

    def method(self):
        return self.a

class ClassA:
    a = 'a'

    def class_b_factory(self):
        return ClassB(self)


instance = ClassA()
instance2 = instance.class_b_factory()
instance2.method()

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