0

I want access to parent self from class inside class

I cant send Parent object to child

Without this solution

parent.Child('Bob jn', Parent)

Like this but this code dosnt work:

class Parent:
    def __init__(self, name):
        self.name = name
    
    class Child:
        def __init__(self, name):
            self.name = name
            self.parentName = Parent.self.name

def main():
    parent = Parent('Bob')
    child = parent.Child('Bob jn')
    print(parent.name)
    print(child.name)
    print(child.parentName) # I nedd this print 'Bob'

main()

I nedd this output:

Bob
Bob jn
Bob
gabriel
  • 42
  • 9
  • Does this answer your question? [How to access outer class from an inner class?](https://stackoverflow.com/questions/2024566/how-to-access-outer-class-from-an-inner-class) The `Child` constructor doesn't have access to any specific instance of `Parent`; surely you have to pass it in. But having nested classes in Python like this is usually not helpful whatsoever and just makes things more confusing, such as in this case. `Parent` refers to the class itself, and `self` only works within an instance of a class, so `Parent.self` is not correct at all. – Random Davis May 10 '22 at 15:19
  • https://stackoverflow.com/questions/42901437/nested-classes-how-to-use-function-from-parent-class In short: don't. – Achille G May 10 '22 at 15:19
  • 1
    @AchilleG maybe this post should be flagged as a duplicate of that one, then – Random Davis May 10 '22 at 15:22
  • Does this answer your question? [nested classes - how to use function from parent class?](https://stackoverflow.com/questions/42901437/nested-classes-how-to-use-function-from-parent-class) – Achille G May 10 '22 at 15:27
  • No way, I think you are confused about inner class with inherent concepts. The inner class's instance has no idea/context of the outer class's instance's creation. Think that they are two separate instances. the 'Bob jn' can access Parent' class attribute, but no way to access an Parent instance's attribute. – Menglong Li May 10 '22 at 15:27

0 Answers0