python - python 构造函数中缺少 1 个必需的位置参数

标签 python

我正在尝试学习 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/

相关文章:

python - 在进程之间共享不断发展的字典

python - 根据其他列的值在多索引数据框中创建新列的简单方法

python - 计时函数并获取返回值

python - 将带有撇号的单词计为一个单词但返回两个单词(python)

python - 我应该使用 SQLObject、SQLAlchemy 还是 SQLAlchemy + Elixir?

python - Django facebook 应用程序 : missing signed_request

python - 如何使用opencv填充整个内部轮廓

python - 子进程生成与父进程相同的 "random"数字

python - Django flatpages 不工作

python - 如何修复 Python 对象的破坏方法?