[英]How can i have 2 classes reference the same instance of a class
我有A類B類和C類。
類A和B會影響類C。因此,它們需要引用該類的同一實例。
#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
我需要如何導入和實例化類才能使其以這種方式工作? 我是編程的新手,仍然在學習,所以對於我來說,顯而易見的事情仍然有些困難。
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)
像那樣的東西
根據您所擁有的內容,我認為最簡單的方法是從模塊a
導入Cinstance
。
from a import Cinstance
您可以將A和B的實例傳遞給C.__init__
方法,並將它們另存為C的屬性。
我在用手機,因此下面的代碼未經測試
class C(object):
def __init__(self, a, b):
self.a = a
self.b = b
>>> c = C(A(), B())
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.