Python 连接字段和值
我的课程结构如下:Python 连接字段和值,python,Python,我的课程结构如下: class A(object): array = [1] def __init__(self): pass class B(A): array = [2, 3] def __init__(self): super(B, self).__init__() class C(B): array = [4] def __init__(self): super(C, self)._
class A(object):
array = [1]
def __init__(self):
pass
class B(A):
array = [2, 3]
def __init__(self):
super(B, self).__init__()
class C(B):
array = [4]
def __init__(self):
super(C, self).__init__()
print array
当我这样做的时候:
c = C()
我希望它按照继承的顺序连接所有字段。并打印[1,2,3,4]。我该怎么做呢?当您在每个类中定义
数组时,它将覆盖继承类的值
如果要执行此操作,请更改类定义,并将数组
初始化添加到每个类的\uuuu init\uuuuu(self)
函数中
即
要使类在类定义时修改它们的类属性(每个类定义中没有样板代码),您需要一个类装饰器或元类
如果使用类装饰器,则必须单独装饰每个类
如果您使用元类,类a
的元类将被类B
和类C
继承,因此您只需修改类a
:
class MetaA(type):
def __init__(cls, name, bases, clsdict):
super(MetaA, cls).__init__(name, bases, clsdict)
for base in bases:
if hasattr(base, 'array'):
cls.array = base.array + cls.array
break
class A(object):
__metaclass__ = MetaA
array = [1]
def __init__(self):
pass
class B(A):
array = [2, 3]
def __init__(self):
super(B, self).__init__()
class C(B):
array = [4]
def __init__(self):
super(C, self).__init__()
屈服
print(A.array)
# [1]
print(B.array)
# [1, 2, 3]
print(C.array)
# [1, 2, 3, 4]
有没有办法在类构造函数中编写一些东西来为其所有子类连接array
?这不是一个好的解决方案,因为它将修改array
的基类值,而不仅仅是为子类创建连接版本。实例化C
后,A.array
也将等于[1,2,3,4]
。另外,如果实例化C
两次,A.array
将变成[1,2,3,4,4]
,依此类推。
print(A.array)
# [1]
print(B.array)
# [1, 2, 3]
print(C.array)
# [1, 2, 3, 4]