python - 类型错误 : method() takes 1 positional argument but 2 were given

标签 python python-3.x methods arguments self

如果我有课...

class MyClass:

    def method(arg):
        print(arg)

...我用来创建对象...

my_object = MyClass()

...我在上面调用 method("foo") 就像这样...

>>> my_object.method("foo")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: method() takes exactly 1 positional argument (2 given)

...为什么 Python 告诉我我给了它两个参数,而我只给了一个参数?

最佳答案

在 Python 中,这个:

my_object.method("foo")

...是 syntactic sugar ,解释器在幕后翻译成:

MyClass.method(my_object, "foo")

...正如你所见,它确实有两个参数——只是从调用者的角度来看,第一个参数是隐含的。

这是因为大多数方法都对它们被调用的对象做一些工作,所以需要有某种方法可以在方法内部引用该对象。按照惯例,第一个参数在方法定义中称为 self:

class MyNewClass:

    def method(self, arg):
        print(self)
        print(arg)

如果您在 MyNewClass 的实例上调用 method("foo"),它会按预期工作:

>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo

偶尔(但不经常),你真的关心你的方法绑定(bind)到的对象,在这种情况下,你可以decorate内置staticmethod()的方法功能这么说:

class MyOtherClass:

    @staticmethod
    def method(arg):
        print(arg)

...在这种情况下,您不需要在方法定义中添加 self 参数,它仍然有效:

>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo

关于python - 类型错误 : method() takes 1 positional argument but 2 were given,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23944657/

相关文章:

python - 旧的 TensorFlow RNN 文件到哪里去了?

python - OpenCV 仿射变换不会执行

python - 如何更改操作系统栏中的 tkinter 默认标题?

python - AES 256 字节以外(8 或 16)

javascript - 从数组中的对象方法访问数组

python - 字符串表达式的递归括号解析器

python - 将值合并到有序字典中的一个键

Python3。类、继承

methods - 从转换为具有 asType 的类的 Groovy 映射中调用方法

访问成员 unordered_map 中的数据时,C++ const 方法在结构中编译错误