Python 类型错误:method() 需要 1 个位置参数,但给出了 2 个
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23944657/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: method() takes 1 positional argument but 2 were given
提问by Zero Piraeus
If I have a class...
如果我有一堂课...
class MyClass:
def method(arg):
print(arg)
...which I use to create an object...
...我用来创建一个对象...
my_object = MyClass()
...on which I call method("foo")
like so...
......我这样称呼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)
...why does Python tell me I gave it two arguments, when I only gave one?
...为什么 Python 告诉我我给了它两个参数,而我只给了一个参数?
采纳答案by Zero Piraeus
In Python, this:
在 Python 中,这是:
my_object.method("foo")
...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:
这是因为大多数方法都会对调用它们的对象进行一些工作,因此需要有某种方式在方法内部引用该对象。按照惯例,第一个参数self
在方法定义中调用:
class MyNewClass:
def method(self, arg):
print(self)
print(arg)
If you call method("foo")
on an instance of MyNewClass
, it works as expected:
如果您调用method("foo")
的实例MyNewClass
,它会按预期工作:
>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo
Occasionally (but not often), you really don'tcare about the object that your method is bound to, and in that circumstance, you can decoratethe method with the builtin staticmethod()
function to say so:
偶尔(但不是经常),你真的不关心你的方法绑定到的对象,在这种情况下,你可以用内置函数装饰方法staticmethod()
来这样说:
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:
...在这种情况下,您不需要向self
方法定义添加参数,它仍然有效:
>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo
回答by Jonru2016
Something else to consider when this type of error is encountered:
遇到此类错误时需要考虑的其他事项:
I was running into this error message and found this post helpful. Turns out in my case I had overridden an __init__()
where there was object inheritance.
我遇到了这个错误消息,发现这篇文章很有帮助。事实证明,在我的情况下,我已经覆盖了一个__init__()
存在对象继承的地方。
The inherited example is rather long, so I'll skip to a more simple example that doesn't use inheritance:
继承的例子比较长,所以我将跳到一个不使用继承的更简单的例子:
class MyBadInitClass:
def ___init__(self, name):
self.name = name
def name_foo(self, arg):
print(self)
print(arg)
print("My name is", self.name)
class MyNewClass:
def new_foo(self, arg):
print(self)
print(arg)
my_new_object = MyNewClass()
my_new_object.new_foo("NewFoo")
my_bad_init_object = MyBadInitClass(name="Test Name")
my_bad_init_object.name_foo("name foo")
Result is:
结果是:
<__main__.MyNewClass object at 0x033C48D0>
NewFoo
Traceback (most recent call last):
File "C:/Users/Orange/PycharmProjects/Chapter9/bad_init_example.py", line 41, in <module>
my_bad_init_object = MyBadInitClass(name="Test Name")
TypeError: object() takes no parameters
PyCharm didn't catch this typo. Nor did Notepad++ (other editors/IDE's might).
PyCharm 没有发现这个错字。Notepad++(其他编辑器/IDE 的可能)也没有。
Granted, this is a "takes no parameters" TypeError, it isn't much different than "got two" when expecting one, in terms of object initialization in Python.
诚然,这是一个“不带参数”的类型错误,就 Python 中的对象初始化而言,它与期望一个时的“得到两个”没有太大区别。
Addressing the topic: An overloading initializer will be used if syntactically correct, but if not it will be ignored and the built-in used instead. The object won't expect/handle this and the error is thrown.
解决这个问题:如果语法正确,将使用重载初始化程序,但如果不正确,它将被忽略并使用内置程序代替。该对象不会期望/处理此问题,并且会引发错误。
In the case of the sytax error: The fix is simple, just edit the custom init statement:
在语法错误的情况下:修复很简单,只需编辑自定义 init 语句:
def __init__(self, name):
self.name = name
回答by Trinadh Koya
It occurs when you don't specify the no of parameters the __init__()
or any other method looking for.
当您没有指定参数__init__()
或任何其他方法寻找的参数时,就会发生这种情况。
For example:
例如:
class Dog:
def __init__(self):
print("IN INIT METHOD")
def __unicode__(self,):
print("IN UNICODE METHOD")
def __str__(self):
print("IN STR METHOD")
obj=Dog("JIMMY",1,2,3,"WOOF")
When you run the above programme, it gives you an error like that:
当你运行上面的程序时,它会给你一个这样的错误:
TypeError: __init__() takes 1 positional argument but 6 were given
类型错误:__init__() 需要 1 个位置参数,但给出了 6 个
How we can get rid of this thing?
我们怎样才能摆脱这个东西?
Just pass the parameters, what __init__()
method looking for
只传参数,__init__()
找什么方法
class Dog:
def __init__(self, dogname, dob_d, dob_m, dob_y, dogSpeakText):
self.name_of_dog = dogname
self.date_of_birth = dob_d
self.month_of_birth = dob_m
self.year_of_birth = dob_y
self.sound_it_make = dogSpeakText
def __unicode__(self, ):
print("IN UNICODE METHOD")
def __str__(self):
print("IN STR METHOD")
obj = Dog("JIMMY", 1, 2, 3, "WOOF")
print(id(obj))
回答by Ruan Nawe
Pass cls
parameter into @classmethod
to resolve this problem.
通过cls
参数转换@classmethod
,以解决此问题。
@classmethod
def test(cls):
return ''
回答by simhumileco
In simple words.
用简单的话来说。
In Python you should add self
argument as the first argument to all defined methods in classes:
在 Python 中,您应该将self
参数添加为类中所有已定义方法的第一个参数:
class MyClass:
def method(self, arg):
print(arg)
Then you can use your method according to your intuition:
然后你可以根据你的直觉使用你的方法:
>>> my_object = MyClass()
>>> my_object.method("foo")
foo
This should solve your problem :)
这应该可以解决您的问题:)
For a better understanding, you can also read the answers to this question: What is the purpose of self?
为了更好地理解,您还可以阅读这个问题的答案:自我的目的是什么?
回答by Stanislav Pankevich
Newcomer to Python, I had this issue when I was using the Python's **
feature in a wrong way. Trying to call this definition from somewhere:
Python 的新手,当我**
以错误的方式使用 Python 的功能时,我遇到了这个问题。试图从某个地方调用这个定义:
def create_properties_frame(self, parent, **kwargs):
using a call without a double star was causing the problem:
使用没有双星的呼叫导致了问题:
self.create_properties_frame(frame, kw_gsp)
TypeError: create_properties_frame() takes 2 positional arguments but 3 were given
类型错误:create_properties_frame() 需要 2 个位置参数,但给出了 3 个
The solution is to add **
to the argument:
解决方案是**
在参数中添加:
self.create_properties_frame(frame, **kw_gsp)
回答by Coddy
You should actually create a class:
您实际上应该创建一个类:
class accum:
def __init__(self):
self.acc = 0
def accumulator(self, var2add, end):
if not end:
self.acc+=var2add
return self.acc