Parent
类由多个其他类继承
class Parent(object):
V_1 = set()
V_2 = set()
ALL_V_ELEMENTS = V_1 | V_2
class Child1(Parent):
V_1 = {1, }
V_2 = {4, 7, 10}
class Child2(Parent):
V_1 = {'a', 'b'}
V_2 = {'a', 'c'}
V_1
和V_2
在每个子级中都是不同的(而且它们在类创建后不会改变)
使用下面的代码,我得到了ALL_V_ELEMENTS
的相同值:
print(Parent.ALL_V_ELEMENTS) # prints: set()
print(Child1.ALL_V_ELEMENTS) # prints: set()
print(Child2.ALL_V_ELEMENTS) # prints: set()
这是我不想要的我需要的是这个:
print(Parent.ALL_V_ELEMENTS) # prints: set()
print(Child1.ALL_V_ELEMENTS) # prints: {1, 10, 4, 7}
print(Child2.ALL_V_ELEMENTS) # prints: {'a', 'c', 'b'}
为了实现我的目标,我可以如下定义类:
class Child1(Parent):
V_1 = {1, }
V_2 = {4, 7, 10}
ALL_V_ELEMENTS = V_1 | V_2
class Child2(Parent):
V_1 = {'a', 'b'}
V_2 = {'a', 'c'}
ALL_V_ELEMENTS = V_1 | V_2
然而,在Parent
的每个子级上复制粘贴ALL_V_ELEMENTS = V_1 | V_2
似乎不是一个好主意
另一种选择是以不同的方式定义Parent
:
class Parent(object):
V_1 = set()
V_2 = set()
def __init__(self):
self.ALL_V_ELEMENTS = self.V_1 | self.V_2
这将对每个冗余实例执行|
操作
有没有更好的方法来实现我的目标
您可以将其定义为属性:
但是,每次都会重新计算集合。让
__init__
创建集合意味着将为每个实例创建集合您可以在元类中计算集合,因此只有在生成类对象时才会生成集合:
这个元类向任何子类添加一个
ALL_V_ELEMENTS
并集;像这样使用它:演示:
相关问题 更多 >
编程相关推荐