类型错误:()方法需要1位置参数,但分别给予2 [英] TypeError: method() takes 1 positional argument but 2 were given

查看:1934
本文介绍了类型错误:()方法需要1位置参数,但分别给予2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个类...

If I have a class ...

class MyClass:

    def method(arg):
        print(arg)

...我用它来创建一个对象...

... which I use to create an object ...

my_object = MyClass()

...在我称之为办法(富)是这样的...

>>> 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的告诉我,我给它两个参数,当我只给了一个?

... why does Python tell me I gave it two arguments, when I only gave one?

推荐答案

在Python中,这样的:

In Python, this:

my_object.method("foo")

...是语法糖,其中间preTER翻译幕后为:

... is syntactic sugar, which the interpreter translates behind the scenes into:

MyClass.method(my_object, "foo")

......,正如你可以看到,确实有两个参数 - 这只是第一个是隐含的,从调用者的角度来看

... which, as you can see, does indeed have two arguments - it's just that the first one is implicit, from the point of view of the caller.

这是因为大多数的方法做他们呼吁对象的一些工作,所以需要有某种方式该对象的方法内引用。按照惯例,这第一个参数叫做方法定义中:

This is because most methods do some work with the object they're called on, so there needs to be some way for that object to be referred to inside the method. By convention, this first argument is called self inside the method definition:

class MyNewClass:

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

如果你调用办法(富) MyNewClass 的一个实例,它按预期工作:

If you call method("foo") on an instance of MyNewClass, it works as expected:

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

偶尔(但不是经常),你真的的有关你的方法被绑定到,在那种情况下,你可以的装饰与内置的 静态方法() 功能,说出这样的话:

Occasionally (but not often), you really don't care about the object that your method is bound to, and in that circumstance, you can decorate the method with the builtin staticmethod() function to say so:

class MyOtherClass:

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

...在这种情况下,你不需要添加参数的方法定义,它仍然工作:

... in which case you don't need to add a self argument to the method definition, and it still works:

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

这篇关于类型错误:()方法需要1位置参数,但分别给予2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆