我想為子類實體中的繼承屬性分配不同的值。我使用的代碼是
class Parent:
def __init__(self, n=50):
# there are multiple parent attributes like 'n'
# I use just one to reproduce the error
self.n = n
def print_n(self):
print('n =', self.n)
class Child(Parent):
def __init__(self, a=5):
self.a = a
def print_a(self):
print('a =', self.a)
son1 = Child(n=100)
son1.print_n()
錯誤資訊是
son1 = Child(n=100)
TypeError: __init__() got an unexpected keyword argument 'n'
實作目標的正確方法是什么?
我試著把super(). 根據this similar question的答案,在子類的init方法中的init(),但它不起作用。
uj5u.com熱心網友回復:
您Child.__init__需要Parent.__init__明確呼叫;它不會自動發生。如果您不想Child.__init__“知道” Parent.__init__args 是什么,請使用*argsor 在這種情況下**kwargs通過任何不由Child.__init__.
class Parent:
def __init__(self, n=50):
# there are multiple parent attributes like 'n'
# I use just one to reproduce the error
self.n = n
def print_n(self):
print('n =', self.n)
class Child(Parent):
def __init__(self, a=5, *args, **kwargs):
super().__init__(*args, **kwargs)
self.a = a
def print_a(self):
print('a =', self.a)
son1 = Child(n=100)
son1.print_n()
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/481944.html
上一篇:星期數中的Sumif日期
