类可以继承__init __()函数吗?(蟒蛇)

3 python class

创建类时,何时需要使用init()?

对于下面的代码,当我们创建PartTimeEmployee()类时,是否可以从Employee()类继承init()?还是我们应该重新输入?

我发现这两个代码都有效:

class Employee(object):

    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
Run Code Online (Sandbox Code Playgroud)

class Employee(object):

    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 __init__(self,employee_name):
        self.employee_name = employee_name

    def calculate_wage(self,hours):
        self.hours = hours
        return hours * 12.00
Run Code Online (Sandbox Code Playgroud)

这里有某种最佳实践吗?

ick*_*fay 7

没有; __init__与其他任何方法一样继承。正因为如此,但是,你有当你采取特别的预防措施覆盖它。例如,如果我们有一个Person类:

class Person(object):
    def __init__(self, name):
        self.name = name
Run Code Online (Sandbox Code Playgroud)

我们要创建一个名为的新类,以对其Employee进行扩展以添加title属性。我们可以在Person构造函数中重复逻辑:

class Employee(Person):
    def __init__(self, name, title):
        self.name = name
        self.title = title
Run Code Online (Sandbox Code Playgroud)

但是,如果Person还有更多事情要做,您可能不想这样做。相反,您需要使用super显式调用超类的__init__

class Employee(Person):
    def __init__(self, name, title):
        super(Employee, self).__init__(name)
        self.title = title
Run Code Online (Sandbox Code Playgroud)

但是在子类没有其他初始化的简单情况下,可以随意省略__init__;实际上,它将确实从超类继承。

  • @forivall:更改__init__的函数签名有很多很好的用途。实际上,stdlib到处都可以做到这一点。如果您需要一个“工厂函数”,该“工厂函数”对层次结构中的所有类都具有相同的接口,则需要它们为__init__拥有相同的签名,或者使用某些@classmethod来代替……但这并不常见。场景(除非您尝试使用Python编写Java代码)。 (4认同)