[英]Python: Trouble with inheritance and super call
我正在嘗試學習python(幾乎沒有編程經驗),並且在代碼學院中陷入這個問題,無法在子類中重寫基類后從基類調用方法。
這是代碼:
class Employee(object):
"""Models real-life employees!"""
def __init__(self, employee_name):
self.employee_name = employee_name
def calculate_wage(self, hours):
self.hours = hours
return hours * 20.00
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
def full_time_wage(self, hours):
super(PartTimeEmployee, self).calculate_wage(self, hours)
milton = PartTimeEmployee("Milton")
print(milton.full_time_wage(10))
不幸的是,它拋出以下內容:
Traceback (most recent call last):
File "python", line 20, in <module>
File "python", line 17, in full_time_wage
TypeError: calculate_wage() takes exactly 2 arguments (3 given)
因此,某個地方傳遞了太多變量,但是我不知道在哪里。
更新1:
通過僅在第17行傳遞幾個小時來解決Traceback調用。
但是,現在我調用print(milton.full_time_wage(10))
使我None
而不是200。 有人可以啟發我做錯什么嗎?
謝謝
該行需要是:
return super(PartTimeEmployee, self).calculate_wage(hours)
方法調用已通過self。 您必須返回調用方法的結果。
問題是傳遞給函數的第二個self
。
super(PartTimeEmployee, self).calculate_wage(self, hours)
^
當您將self
傳遞給super
,它將自動將super類傳遞給該函數(如果它提供了該函數)。 否則,它將在類__mro__
中的其他庫中查找該函數。
在文檔中閱讀更多信息: https : //docs.python.org/3.6/library/functions.html#super
您不需要使用self作為參數之一來調用calculate_wage():
應該:
class PartTimeEmployee(Employee):
def calculate_wage(self, hours):
self.hours = hours
return hours * 12.00
def full_time_wage(self, hours):
super(PartTimeEmployee, self).calculate_wage(hours)
因此,錯誤消息已由以上所有答案解決。
我的代碼什么也不返回的問題是我忘了第17行的return
叫-我是個白痴。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.