1

I have class A class B and class C.

class A and B can affect class C. so they need to refer to the same instance of the class.

#a.py
from C import C
Cinstance = C()
Cinstance.add()


#b.py
class b(object)
#i need to refer to 'cinstance' here to control the same instance of the class

#C.py
class C(object)
    def __init__(self):
        self.a=1

    def add(self):
        self.a += 1
        print a

How do i need to import and instanciate the classes for it to work this way? I am new to programming and still learning so things that are obvious are still a little difficult for me right now.

1
  • Keep in mind that Python is a case-sensitive language, so Cinstance is not cinstance. Also, you describe a as a class, but in your code it's a module.
    – kojiro
    May 24, 2012 at 23:17

3 Answers 3

3
class A:
    def __init__(self,cInst):
        self.c = cInst

class B:
    def __init__(self,cInst):
        self.c = cInst

cInst = C()

a = A(cInst)
b = B(cInst) 

something like that maybe

2

based on what you have there I think the easiest thing would be to import Cinstance from module a.

from a import Cinstance
0

You can pass an instance of A and B to your C.__init__ method and save them as attributes of C.

I'm on my phone, so the code below isn't tested

class C(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b

>>> c = C(A(), B())

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.