edualvarado
edualvarado

Reputation: 353

Python - Using objects in different classes

How can I use objects which belong to one class, in another different class? I tried different things, but I still do not get a solution. Let´s say I have the following example code:

class ClassA():
    def __init__(self):
        print "I am ClassA"

    def methodA(self):
        print "Method executed"
    
class ClassB():
    def __init__(self):
        print "I am ClassB"
    
        self.varB = 0       

    def methodB(self):       
        if self.varB == 0:
            # Error here
            self.objectA.methodA()
        else:
            print "Method not executed"

class ClassC():
    def __init__(self):
        print "I am ClassC"
    
        self.objectA = ClassA()
        self.objectA.methodA()


#Step 1:
obj1 = ClassC()

#Step 2:
obj2 = ClassB()    

#Step 3: (Gives error)
obj2 = methodB()

In this example, I have three classes. In ClassC, I create an instance of ClassA, which is used to execute the respective method (methodA). If afterwards we procceed with "Step 1", the output is:

I am ClassC

I am ClassA

Method executed

Then, in "Step 2", I create a new object of ClassB. Following to the last output, we get now as well:

I am ClassB

The problems comes with "Step 3", when I execute the methodB for the last object. The error:

AttributeError: ClassB instance has no attribute 'objectA'

I have very clear the origin of the error. I can´t simply use the instance that I created in ClassC, inside the method of ClassB.

Does anyone know, how could I access from ClassB, an instance (in this case objectA) that I created in other class (ClassC)?

Upvotes: 0

Views: 486

Answers (2)

blue note
blue note

Reputation: 29071

The objectA belongs to a specific instance of class C. So, there is no way, you have to pass this instance to the instance of class B somehow. The way you are using it, probably in the constructor of class B:

def __init__(self, c):
    print "I am ClassB"
    self.varB = 0   
    self.objectA = c.objectA

and then

obj2 = ClassB(obj1) 

Upvotes: 1

satyam soni
satyam soni

Reputation: 269

Try Inheritance in Python. Inherit Class A in Class B.

class ClassB(A):
    def __init__(self):
        print "I am ClassB"
        self.varB = 0       

    def methodB(self):       
        if self.varB == 0:
            # Error here
            self.methodA()
        else:
            print "Method not executed"

This should work for you.

Upvotes: 1

Related Questions