我正在尝试学习 python 中的继承概念。我有一个 Employee 类和派生类 Executive。
class Employee:
'Class defined for employee'
def __init__(self, name, dept, salary):
self.name = name
self.dept = dept
self.salary = salary
子类
class Executive(Employee):
def __init__(self, name, dept, salary, hascar):
Employee.__init__(name, dept, salary)
self.hascar = hascar
has car 是传递给构造函数的 bool 值,但是这会给我一个错误:
File "I:\Python_practicals\com\python\oop\Executive.py", line 7, in init Employee.init(name, dept, salary) TypeError: init() missing 1 required positional argument: 'salary'
当我尝试实例化 Executive 的对象时。
emp4 = Executive("Nirmal", "Accounting", 150000, True)
最佳答案
虽然 __init__
是实例方法,但您是在类 而不是实例上调用它。此调用称为未绑定(bind),因为它未绑定(bind)到实例。因此,您需要显式传递 self
:
class Executive(Employee):
def __init__(self, name, dept, salary, hascar):
Employee.__init__(self, name, dept, salary)
# ^^^^
self.hascar = hascar
然而,推荐的方法是使用 super
:
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
使用 super
你的代码看起来像这样:
class Executive(Employee):
def __init__(self, name, dept, salary, hascar):
super(Executive, self).__init__(name, dept, salary)
# ^^^^^^^^^^^^^^^^^^^^^^
self.hascar = hascar
Python 3 添加了一些语法糖来简化这个公共(public)父类调用:
class Executive(Employee):
def __init__(self, name, dept, salary, hascar):
super().__init__(name, dept, salary) # Py 3
# ^^^^^^^
self.hascar = hascar
关于python - python 构造函数中缺少 1 个必需的位置参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52385893/