如果我有课...
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/