mend4x
mend4x

Reputation: 213

Access the method of another class in python

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.

Upvotes: 0

Views: 72

Answers (1)

bruno desthuilliers
bruno desthuilliers

Reputation: 77892

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

Upvotes: 2

Related Questions