簡體   English   中英

在python構造函數中缺少1個必需的位置參數

[英]Missing 1 required positional argument in python Constructor

我正在嘗試學習python中的繼承概念。 我有一個雇員班級和派生班級主管。

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

具有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

但是,推薦的方法是使用super

返回將方法調用委托給類型的父級或同級類的代理對象。 這對於訪問已在類中重寫的繼承方法很有用。

使用super您的代碼將如下所示:

class Executive(Employee):

    def __init__(self, name, dept, salary, hascar):
        super(Executive, self).__init__(name, dept, salary)
#       ^^^^^^^^^^^^^^^^^^^^^^
        self.hascar = hascar

Python 3添加了一些語法糖來簡化此公共父類的調用:

class Executive(Employee):

    def __init__(self, name, dept, salary, hascar):
        super().__init__(name, dept, salary)  # Py 3
#       ^^^^^^^
        self.hascar = hascar

在Python 3.x中
使用super()關鍵字。 這樣可以避免顯式鍵入Base類。 使代碼更具可維護性。

class Executive(Employee):

    def __init__(self, name, dept, salary, hascar):
        super().__init__(name, dept, salary)
        self.hascar = hascar

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM