TypeError: method() takes 1 positional argument but 2 were given(TypeError:method() 接受 1 个位置参数,但给出了 2 个)
问题描述
如果我有课...
class MyClass:
def method(arg):
print(arg)
...我用来创建对象...
...which I use to create an object...
my_object = MyClass()
...我在上面调用 method("foo")
就像这样...
...on which I call method("foo")
like so...
>>> 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")
...是语法糖,解释器在幕后将其翻译成:p>
...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.
这是因为大多数方法都对它们被调用的对象做一些工作,所以需要有某种方法可以在方法内部引用该对象.按照惯例,第一个参数在方法定义中称为 self
:
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
的实例上调用 method("foo")
,它会按预期工作:
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
偶尔(但不经常),你真的不关心你的方法绑定到的对象,在这种情况下,你可以装饰 使用内置 staticmethod()
函数这么说:
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)
...在这种情况下,您不需要在方法定义中添加 self
参数,它仍然有效:
...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
这篇关于TypeError:method() 接受 1 个位置参数,但给出了 2 个的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TypeError:method() 接受 1 个位置参数,但给出了 2 个


基础教程推荐
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01