创建类时,何时需要使用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)
这里有某种最佳实践吗?
没有; __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__;实际上,它将确实从超类继承。
| 归档时间: |
|
| 查看次数: |
249 次 |
| 最近记录: |