TypeError : method ()는 1 개의 위치 인수를 취하지 만 2가 주어졌습니다
수업이 있으면 ...
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)
... 파이썬이 왜 하나만 주었을 때 두 가지 주장을했다고 말합니까?
파이썬에서 이것은 :
my_object.method("foo")
...은 구문 설탕 이며, 해석기는 장면 뒤에서 다음과 같이 번역합니다.
MyClass.method(my_object, "foo")
... 보시다시피, 실제로 두 가지 주장이 있습니다. 발신자의 관점에서 볼 때 첫 번째 주장은 암시 적입니다.
이것은 대부분의 메소드가 호출 된 오브젝트에 대해 일부 작업을 수행하기 때문에 메소드 내에서 해당 오브젝트를 참조 할 수있는 방법이 필요하기 때문입니다. 일반적으로이 첫 번째 인수는 self
메소드 정의 안에서 호출 됩니다.
class MyNewClass:
def method(self, arg):
print(self)
print(arg)
method("foo")
의 인스턴스 를 호출하면 MyNewClass
예상대로 작동합니다.
>>> my_new_object = MyNewClass()
>>> my_new_object.method("foo")
<__main__.MyNewClass object at 0x29045d0>
foo
간혹 (빈번하지는 않지만) 메서드가 바인딩 된 개체를 신경 쓰지 않고 그 상황 에서 내장 함수로 메서드를 장식 하여 다음과 같이 staticmethod()
말할 수 있습니다.
class MyOtherClass:
@staticmethod
def method(arg):
print(arg)
...이 경우 self
메소드 정의에 인수를 추가 할 필요가 없으며 여전히 작동합니다.
>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo
이 유형의 오류가 발생했을 때 고려해야 할 사항 :
이 오류 메시지가 표시되어이 게시물이 도움이되었다는 것을 알았습니다. 내 경우 에는 객체 상속이 있는 init ()를 재정의했습니다 .
상속 된 예제는 다소 길기 때문에 상속을 사용하지 않는 더 간단한 예제로 건너 뛸 것입니다.
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")
결과는 다음과 같습니다
<__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).
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.
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:
def __init__(self, name):
self.name = name
It occurs when you don't specify the no of parameters the __init__()
or any other method looking for.
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
How we can get rid of this thing?
Just pass the parameters, what __init__()
method looking for
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))
In simple words.
In Python you should add self
argument as the first argument to all defined methods in classes:
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?
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:
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
The solution is to add ** to the argument:
self.create_properties_frame(frame, **kw_gsp)
Pass cls
parameter into @classmethod
to resolve this problem.
@classmethod
def test(cls):
return ''
'Programing' 카테고리의 다른 글
Context.startForegroundService ()가 Service.startForeground ()를 호출하지 않았습니다. (0) | 2020.05.10 |
---|---|
npm UNMET PEER DEPENDENCY 경고는 어떻게 수정합니까? (0) | 2020.05.10 |
수업 종류 확인 (0) | 2020.05.10 |
푸시 알림 기술은 Android에서 어떻게 작동합니까? (0) | 2020.05.10 |
jq를 사용하여 내부 배열의 값을 기반으로 객체 배열을 필터링하는 방법은 무엇입니까? (0) | 2020.05.10 |