“TypeError:Person() 采用 1 个位置参数,但给出了 2 个”,但构造函数采用两个参数

use*_*336 0 python

这是最奇怪的事情。我的 python 刚刚停止处理其构造函数中具有多个参数的类?运行 python 3.8.10 出现错误TypeError: Person() takes 1 positional argument but 2 were given

def Person(object):
    def __init__(self, a, b):
        self.aa = a
        self.bb = b

pp = Person(20, 40)
Run Code Online (Sandbox Code Playgroud)

如果我将 Person__init__降低到一个参数,那么它就会起作用。如果我将其提高到 3,则会出现相同的takes 1 but 3 were given错误。我完全被难住了?

Raf*_*Bem 5

你已经声明你的 Person 类是错误的。您使用了def而不是class,这意味着您实际上有一个名为 Person 的函数和一个名为 的本地函数__init__

尝试这个:

class Person(object):
    def __init__(self, a, b):
        self.aa = a
        self.bb = b
Run Code Online (Sandbox Code Playgroud)

  • 也许你睡得不太好?哈哈。这种情况在我们所有人身上至少发生一次,或者对我来说至少每天一次。 (2认同)