Python:继承和支持的问题

2024-07-05 14:53:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试学习python(以前很少有编程经验),但在codeaccademy上遇到了一个问题:在子类中重写基类之后,如何从基类调用方法。你知道吗

代码如下:

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号线上只花了几个小时解决了回溯电话。你知道吗

不过,现在我的结果是 print(milton.full_time_wage(10)) 给我None而不是我预期的200。 有人能告诉我我做错了什么吗?你知道吗

谢谢


Tags: nameselfreturntimedefemployee基类full
3条回答

您不需要使用self作为参数之一调用calculate\u 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)

线路需要:

return super(PartTimeEmployee, self).calculate_wage(hours)

方法调用已传递self。必须返回调用该方法的结果。你知道吗

问题是传递给函数的第二个self。你知道吗

super(PartTimeEmployee, self).calculate_wage(self, hours)
                                              ^

当您将self传递给super时,它将自动将超类传递给函数(如果它提供了该函数)。否则它将在类的其他基中查找函数__mro__。你知道吗

阅读更多文档:https://docs.python.org/3.6/library/functions.html#super

相关问题 更多 >