Python:可以链接属于两个不同类的两个变量吗?
我想把两个变量连接到两个不同的类,但我不知道我想做的是可能的还是不可能的 例如,如果我有这两个类:Python:可以链接属于两个不同类的两个变量吗?,python,class,Python,Class,我想把两个变量连接到两个不同的类,但我不知道我想做的是可能的还是不可能的 例如,如果我有这两个类: class one(): def __init__(self): self.a = 0 def compute(self): self.a = self.a + 1 class two(): def __init__(self): self.a = 0 self.C_one = one()
class one():
def __init__(self):
self.a = 0
def compute(self):
self.a = self.a + 1
class two():
def __init__(self):
self.a = 0
self.C_one = one()
self.link()
def link(self):
self.a = self.C_one.a
def compute(self):
self.C_one.compute()
print('C_one a=',self.C_one.a )
print('C_two a=',self.a )
C_two = two()
for i in range(5):
C_two.compute()
在类two
中,我想将变量a
与类one
的变量a
连接起来,因此每次执行cutwo.compute时,我不必显式调用self.a=self.cuone.a
示例中的代码告诉我:
C_one a= 1
C_two a= 0
C_one a= 2
C_two a= 0
C_one a= 3
C_two a= 0
C_one a= 4
C_two a= 0
C_one a= 5
C_two a= 0
这不是我期望的结果。
有人知道我能不能用python来做吗
更新
从下面的例子
class one():
def __init__(self):
self.a = 0
def compute(self):
self.a = self.a + 1
class two():
def __init__(self):
self.a = 0
class three():
def __init__(self):
self.C_one = one()
self.C_two = two()
self.b = 0
def compute(self):
self.C_one.compute()
#self.C_two.a = self.C_one.a
print('C_one a=',self.C_one.a )
print('C_two a=',self.C_two.a )
C_three = three()
for i in range(5):
C_three.compute()
是否可以使用deceze的答案并用属性替换注释行#self.C_two.a=self.C_one.a
?就像类one
和two
在类three
中链接一样
deceze的回答
将two.a
定义为:
谢谢你的回答。我更新了这个问题,因为我想知道是否可以使用我们的答案在第三个类中连接两个类(如第二个示例)?问题在于two()
创建自己的one()
与one()
中实例化的one()
无关。这里的解决方案是依赖注入:two(self.C\u one)
。因此在第二个示例中,我必须在类one()
和two()之间创建直接连接(反之亦然)。因此,我必须在两个类的\uuuu init\uuuu()
中创建一个()的实例(反之亦然)?根据经验,在\uuu init\uuuu>中创建其他类的实例是不好的做法。相反,您应该执行定义初始化(self,one):self.C\u one=one
。然后您将有一个地方执行one()
,并将该实例作为构造函数参数传递给任何其他需要它的类。→ 这叫做依赖注入。好的,谢谢。我将检查我不知道的依赖注入。
class one():
def __init__(self):
self.a = 0
def compute(self):
self.a = self.a + 1
class two():
def __init__(self,one):
self.C_one = one
@property
def a(self):
return self.C_one.a
class three():
def __init__(self):
self.C_one = one()
self.C_two = two(self.C_one)
self.b = 0
def compute(self):
self.C_one.compute()
print('C_one a=',self.C_one.a )
print('C_two a=',self.C_two.a )
C_three = three()
for i in range(5):
C_three.compute()
class two:
def __init__(self):
self.C_one = one()
@property
def a(self):
return self.C_one.a
...