在具有给定类层次结构的Python 3.x中,SubClassZero
和SubClassOne
继承自SuperClass
;
class SuperClass(object):
def __init__(self, *args, **kwargs):
self.thing_zero = "Inherited string."
class SubClassZero(SuperClass):
def __init__(self, *args, **kwargs):
SuperClass.__init__(self, *args, **kwargs)
self.thing_one = "SubClassZero's string."
class SubClassOne(SuperClass):
def __init__(self, *args, **kwargs):
SuperClass.__init__(self, *args, **kwargs)
self.thing_one = "SubClassOne's string."
scz = SubClassZero()
sco = SubClassOne()
如果我们想让子类能够从kwarg
设置标题,那么可以使用构建的__init__
函数重新定义SuperClass的setattr
函数;
def __init__(self, *args, **kwargs):
self.thing_zero = "Inherited string."
if 'title' in kwargs:
self.title = kwargs['title']
else:
self.title = ""
setattr(SuperClass, '__init__', __init__)
但要做到这一点,必须知道__init__
的先前结构才能保持全部功能。有没有办法以某种方式添加__init__
SuperClass
函数而不完全覆盖它?