派生类的python构造函数
作者:互联网
class baseClass():
def __init__(self,mark,name):
self.mark = mark
self.name = name
class derivedClass(baseClass):
b1 = derivedClass(name='Jibin')
print b1.name
这是我的代码最初&它工作得很好.
(注意:我无法访问baseClass)
但后来我不得不将另一个属性等级传递给derivedClass.所以我编辑了这样的代码.
class baseClass():
def __init__(self,mark,name):
self.mark = mark
self.name = name
class derivedClass(baseClass):
def __init__(self,rank):
self.rank = rank
b1 = derivedClass(name='Jibin')
print b1.name
这导致错误__init __()得到一个意外的关键字参数’name’
这是预期的,因为derivedClass的__init__没有参数名称.
我不想在真正的baseClass中为derivedClass b’cos的__init__添加一个额外的参数名称,而是有10个参数而不是2个(标记,名称)&如果我将所有这些作为附加参数提供给derivedClass,我将会混淆其参数列表.
注意:我知道使用baseClass初始化baseClass .__ init __(self)或super(derivedClass,self).__ init __()
解决方法:
也许你可以尝试这样的事情
class BaseClass(object):
def __init__(self, mark=None, name=None): # you're using named parameters, declare them as named one.
self.mark = mark
self.name = name
class DerivedClass(BaseClass): # don't forget to declare inheritance
def __init__(self, rank, *args, **kwargs): # in args, kwargs, there will be all parameters you don't care, but needed for baseClass
super(DerivedClass, self).__init__(*args, **kwargs)
self.rank = rank
b1 = derivedClass(name='Jibin')
print b1.name
标签:base-class,derived-class,python,super 来源: https://codeday.me/bug/20190826/1732496.html