0

Let's say i have two classes in such a way:

class Class1(ParentClass1):
    def __init__(self):
        super(Class1, self).__init__()
        c2 = Class2()

    def foo(self):
        pass

class Class2(ParentClass2):
    def __init__(self):
        super(Class2, self).__init__()

    def bar(self):
        foo() # from Class1

how to access foo() from Class2 if instance of Class2 is created in Class1, while Class1 itself is initiated in another class?

In other words, the dialog box(Class2) must update the list from Class1.

UPDATE

Initially, I had an instance of Class0 in __name__ == '__main__'. Class0 creates the instance of Class1 then I could access the instance of Class1 through Class2, but I need to create an instance of Class0 on some main() function, which disallows me access the Class1 methods.

4
  • 1
    You couldn't do that without an instance of Class1. Maybe pass one as an argument to bar? Commented Feb 19, 2020 at 15:37
  • 1
    @rassar, you mean pass an instance of Class1 to bar() as an argument? Commented Feb 19, 2020 at 15:39
  • 1
    Exactly, or an argument to __init__, and have Class2 store an instance of Class1. Commented Feb 19, 2020 at 15:40
  • @rassar, you're right! i'm really ashamed of myself. You can post it as an answer Commented Feb 19, 2020 at 15:49

1 Answer 1

2

Proper terminology helps... You don't want to access "method of Class1", but "method of an instance of Class1" - which means you need to pass an instance of Class1 to your instance of Class2:

class Class1(ParentClass1):
    def __init__(self):
        super(Class1, self).__init__()
        self.c2 = Class2(self)
        self.c2.bar()

    def foo(self):
        print("foo")

class Class2(ParentClass2):
    def __init__(self, c1):
        super(Class2, self).__init__()
        self.c1 = c1

    def bar(self):
        self.c1.foo() 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.