[英]How to pass arguments to parent class with inheritance and with super keyword?
[英]inheritance — keyword and regular arguments in parent class
如果我做對了,那么調用ChildFoo實例的正確方法是什么? 我之所以這樣問是因為我知道我應該將參數放在關鍵字參數之前,但是不知道在這種情況下該怎么做...
class ParentFoo(object):
def __init__(self,a,b,c=None):
pass
class ChildFoo(ParentFoo):
def __init__(self,d,e,f=None):
ParentFoo.__init__(self, a, b, c = "fing")
像這樣嗎
class ParentFoo(object):
def __init__(self,a,b,c=None):
print(c)
class ChildFoo(ParentFoo):
def __init__(self,d,e,f=None):
super(ChildFoo,self).__init__(d,e,c="fing")
c = ChildFoo("1","2")
官方python文檔在這里https://docs.python.org/2/library/functions.html#super
由於ChildFoo
從ChildFoo
繼承, ParentFoo
它還必須為父類獲取參數
class ChildFoo(ParentFoo):
def __init__(self, a, b, d, e, f=None):
ParentFoo.__init__(self, a, b, c="fing")
我不添加' ChildFoo
因為似乎當ChildFoo
初始化ParentFoo
時您想要默認值。 或者,您可以為所有父參數提供默認值
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.