简体   繁体   English

2个或更多类的属性之间的依赖关系

[英]Dependencies between attributes of 2 and more classes

Is it possible to initialize instances of classes with attributes that are dependent across (not in circular way)?是否可以初始化具有相互依赖的属性的类的实例(不是循环方式)?

Today, I use dictionaries instead of classes as follows:今天,我使用字典而不是类,如下所示:

dictA = {'A1': 10}
dictB = {'B1': 2}
dictB['B2'] = dictA['A1'] * dictB['B1']
dictA['A2'] = dictB['B2'] * 3  # dictA['A1'] * dictB['B1'] * 3

print(dictA)  # {'A1': 10, 'A2': 60}
print(dictB)  # {'B1': 2, 'B2': 20}

When I try to express the above with classes, I end up with RecursionError: maximum recursion depth exceeded .当我尝试用类表达上述内容时,我最终得到RecursionError: maximum recursion depth exceeded

class A:
    def __init__(self):
        self.A1 = 10
        self.A2 = B().B2 * 3

class B:
    def __init__(self):
        self.B1 = 2
        self.B2 = self.B1 * A().A1
    
a = A()
b = B()

The dictionaries (classes) are separate because they represent different types of data (eg employees and time).字典(类)是分开的,因为它们代表不同类型的数据(例如员工和时间)。

You need to make the initializers non-circular.您需要使初始化程序非循环。 Then you can use @property to lazily evaluate the properties然后你可以使用@property懒惰地评估属性

class A:
    def __init__(self):
        self.A1 = 10

    @property
    def A2(self):
        return B().B2 * 3


class B:
    def __init__(self):
        self.B1 = 2

    @property
    def B2(self):
        return self.B1 * A().A1


a = A()
b = B()

print(a.A1, a.A2, b.B1, b.B2)

Result:结果:

10 60 2 20

Another alternative:另一种选择:

class A:
    def __init__(self):
        self.A1 = 10
    def add_A2(self, x):
        self.A2 = x.B2 * 3

class B:
    def __init__(self):
        self.B1 = 2
    def add_B2(self, x):
        self.B2 = self.B1 * x.A1
    
a = A()
b = B()
b.add_B2(a)
a.add_A2(b)

You get a RecursionError because you create an instance of B to set A2 , and to create an instance of B you need to create an instance of A to set B2 .你得到一个RecursionError因为你创建了一个B的实例来设置A2 ,并且要创建一个B的实例,你需要创建一个A的实例来设置B2 You will keep creating instances of A and B in a circular manner.您将继续以循环方式创建AB的实例。

You can declare class attributes, which can be used without creating an instance of the class.您可以声明 class 属性,无需创建 class 的实例即可使用。 Note that this value is always the same for all instances of a class.请注意,对于 class 的所有实例,此值始终相同。 So you can use it for a value like days_of_week = 7 , but not for a persons age age = 34 , as a persons age is not always 34.因此,您可以将其用于像days_of_week = 7这样的值,但不能用于age = 34的人,因为人的年龄并不总是 34 岁。

Assuming A1 and A2 can be class attributes, which are always the same, you could do the following:假设A1A2可以是 class 属性,它们始终相同,您可以执行以下操作:

class A:
    A1 = 10
    def __init__(self):
        self.A2 = B.B1 * self.A1 * 3
    
class B:
    B1 = 2
    def __init__(self):
        self.B2 = self.B1 * A.A1
        
a = A()
b = B()
print(a.A1, a.A2)
print(b.B1, b.B2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM