在您的 BaseB__init__
函数中,您调用的是 Child 的作者,而不是 Parent 的作者。如果你想打电话给父母的作者,你会使用BaseB.authors
而不是self.authors
:
class BaseA(object):
authors = ['a', 'b']
author_list = authors
class BaseB(object):
authors = ['a', 'b']
def __init__(self, *arg, **kwargs):
self.author_list = BaseB.authors
class ChildA(BaseA):
authors = ['c', 'd']
class ChildB(BaseB):
authors = ['c', 'd']
child_a = ChildA()
child_b = ChildB()
print(child_a.author_list)
print(child_b.author_list)
>>> ['a', 'b']
>>> ['a', 'b']
如果您将连接 ParentB 和 ChildB 的作者,那么您将同时使用BaseB.authors
and self.authors
:
class BaseA(object):
authors = ['a', 'b']
author_list = authors
class BaseB(object):
authors = ['a', 'b']
def __init__(self, *arg, **kwargs):
self.author_list = BaseB.authors + self.authors
class ChildA(BaseA):
authors = ['c', 'd']
class ChildB(BaseB):
authors = ['c', 'd']
child_a = ChildA()
child_b = ChildB()
print(child_a.author_list)
print(child_b.author_list)
>>> ['a', 'b']
>>> ['a', 'b', 'c', 'd']
覆盖
class BaseA(object):
authors = ['a', 'b']
author_list = authors
class BaseB(object):
authors = ['a', 'b']
def __init__(self, *arg, **kwargs):
self.author_list = self.authors
class ChildA(BaseA):
authors = ['c', 'd']
def __init__(self, *arg, **kwargs):
self.author_list = self.authors
class ChildB(BaseB):
authors = ['c', 'd']
child_a = ChildA()
child_b = ChildB()
print(child_a.author_list)
print(child_b.author_list)
>>> ['c', 'd']
>>> ['c', 'd']