0

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

1
  • You should use new style classes in python 2: inherit from object: class A(object): or better yet, python 3... That said, you cannot do what you intend to do Commented Jul 24, 2018 at 12:21

2 Answers 2

1

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

1 Comment

It worked perfectly, and it makes all the sense of the world. Thank you.
1

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.

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.