0

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()

1 Answer 1

4

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()
Sign up to request clarification or add additional context in comments.

1 Comment

@thefourtheye: It's the correct name to use though; classes are instance factories, meta classes are class factories, etc. When using a function solely to produce an object in a specific context, using factory in the name is fine, unless the specific context gives you a better name. There is no context here to speak of though..

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.