【问题标题】:Why am I getting a TypeError when I seem to be filling the paremeters? [closed]当我似乎正在填写参数时,为什么会收到 TypeError? [关闭]
【发布时间】:2021-11-09 01:44:29
【问题描述】:

我正在尝试创建一个对象,并首先使用 2 个字段(名称和编号)对其进行初始化。但是每次我运行程序时都会出现这个错误:

TypeError: __init__() missing 1 required positional argument: 'number'

类中的__init__ 方法如下所示:

    def __init__(self, name, number):
    self.__name__ = name
    self.__number__ = number

我尝试创建对象的代码是这样的:

employee1 = ProductionWorker(Employee)

name = input("Enter employee name:")
number = input("Enter employee number:")

employee1.__init__(name, number)

有人知道我为什么会收到这个错误吗?

【问题讨论】:

  • __init__ 方法需要两个参数:名称和编号。你在employee1 = ProductionWorker(Employee)中只提供了一个参数
  • 我认为我需要在创建对象employee1 后为其添加信息。如果是问题,我将如何解决?
  • 你不应该明确地调用__init____init__ 在您实例化对象时由解释器自动调用(例如 ProductionWorker(name, number)。)
  • 你这里有一些非常基本的误解,你应该重新阅读你的 Python OOP 教程。
  • 什么是ProductionWorker?请用这个缺失的细节更新您的问题。

标签: python object typeerror


【解决方案1】:

做:

name = input("Enter employee name:")
number = input("Enter employee number:")

employee1 = ProductionWorker(name, number)

您通常不需要显式调用__init__;它由ProductionWorker(...) 表达式调用,该表达式将其参数作为初始化的一部分传递给self.__init__

在构造Employee是父类的新对象时,不需要重述;只有在定义类时才需要说明。

【讨论】:

  • 非常感谢你解决了我的问题我明白我现在是如何误解了
【解决方案2】:

您正在使用类作为参数。 然后,init 总是在创建时自动调用。这可能是你想要的工作方式(使用 show 方法进行验证):

class Employee:
    def __init__(self, name, number):
        self.__name__ = name
        self.__number__ = number
    

    def show(self):
        print(self.__name__)
        print(self.__number__)
    

name = input("Enter employee name:")
number = input("Enter employee number:")
employee1 = Employee(name,number)
employee1.show()  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-21
    • 2022-07-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2018-05-04
    • 2013-09-08
    相关资源
    最近更新 更多