Python:是否可以链接属于两个不同类的两个变量?

问题描述 投票:4回答:1

我想将两个变量连接到两个不同的类但我不知道我正在尝试做的是否可能。

例如,如果我有这两个类:

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与类a的变量one连接起来,所以每次执行self.a = self.C_one.a时我都不必显式调用C_two.compute

示例中的代码给了我这个:

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?就像那些类onetwo在类three中相关联。

来自deceze的回答

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()
python class
1个回答
7
投票

two.a定义为property

class two:
    def __init__(self):
        self.C_one = one()

    @property
    def a(self):
        return self.C_one.a

    ...
© www.soinside.com 2019 - 2024. All rights reserved.