我正在尝试学习python中的继承概念。我有一个雇员班级和派生班级主管。
class Employee:
'Class defined for employee'
def __init__(self, name, dept, salary):
self.name = name
self.dept = dept
self.salary = salary
Run Code Online (Sandbox Code Playgroud)
子类
class Executive(Employee):
def __init__(self, name, dept, salary, hascar):
Employee.__init__(name, dept, salary)
self.hascar = hascar
Run Code Online (Sandbox Code Playgroud)
具有car是传递给构造函数的布尔值,但是这会给我一个错误:
init Employee中的文件“ I:\ Python_practicals \ com \ python \ oop \ Executive.py”,第7行 。初始化(名称,部门,薪金)TypeError:初始化()缺少1个必需的位置参数:'salary'
当我尝试实例化Executive对象时。
emp4 = Executive("Nirmal", "Accounting", 150000, True)
虽然__init__是实例方法,但您是在类而不是实例上调用它。该调用称为unbound,因为它未绑定到实例。因此,您需要显式传递self:
class Executive(Employee):
def __init__(self, name, dept, salary, hascar):
Employee.__init__(self, name, dept, salary)
# ^^^^
self.hascar = hascar
Run Code Online (Sandbox Code Playgroud)
但是,推荐的方法是使用super:
返回将方法调用委托给类型的父级或同级类的代理对象。这对于访问已在类中重写的继承方法很有用。
用super你的代码看起来像这样:
class Executive(Employee):
def __init__(self, name, dept, salary, hascar):
super(Executive, self).__init__(name, dept, salary)
# ^^^^^^^^^^^^^^^^^^^^^^
self.hascar = hascar
Run Code Online (Sandbox Code Playgroud)
Python 3添加了一些语法糖来简化此公共父类的调用:
class Executive(Employee):
def __init__(self, name, dept, salary, hascar):
super().__init__(name, dept, salary) # Py 3
# ^^^^^^^
self.hascar = hascar
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5188 次 |
| 最近记录: |