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)
...왜 파이톤은 내가 두 번 언쟁을 했다고 말하는가, 내가 한 번밖에 안 했는데?
Python에서는 다음 작업을 수행하십시오.
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
간혹(그러나 자주는 아님) 자신의 방법이 속박되어 있는 대상에는 정말로 신경을 쓰지 않으며, 그러한 상황에서는 다음과 같이 말하는 내장된 기능으로 방법을 장식할 수 있다.
class MyOtherClass:
@staticmethod
def method(arg):
print(arg)
...이 경우 a를 추가할 필요가 없는 경우self
메서드 정의에 대한 인수, 여전히 작동:
>>> my_other_object = MyOtherClass()
>>> my_other_object.method("foo")
foo
간단히 말하면.
Python에서 당신은 추가해야 한다.self
클래스에 정의된 모든 방법에 대한 첫 번째 인수:
class MyClass:
def method(self, arg):
print(arg)
그러면 직관에 따라 방법을 사용할 수 있다.
>>> my_object = MyClass()
>>> my_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은 이 오타를 알아채지 못했다.메모장++(다른 편집자/IDE의 힘)도 아니었다.
물론, 이것은 "매개변수 없음" TypeError로, Python에서 개체 초기화 측면에서 예상했을 때 "got 2"와 크게 다르지 않다.
주제 설명:구문적으로 맞으면 과부하 이니셜라이저가 사용되지만 그렇지 않으면 무시되고 내장된 이니셜라이저가 대신 사용된다.그 물체는 이것을 예상/처리하지 않을 것이고 오류가 던져진다.
sytax 에러가 발생한 경우:수정은 간단하므로 사용자 정의 초기화 문을 편집하십시오.
def __init__(self, name):
self.name = name
는 Python Pythone을 사용할 때 이**
비뚤어진 모습을 드러내다이 정의를 어디선가 호출하려고 하는 중:
def create_properties_frame(self, parent, **kwargs):
이중 별 없이 전화를 사용하는 것은 문제를 야기했다:
self.create_properties_frame(frame, kw_gsp)
TypeError: create_properties_frame()는 2개의 위치 인수를 사용하지만 3개가 지정됨
해결책은 추가하는 것이다.**
다음과 같은 논거:
self.create_properties_frame(frame, **kw_gsp)
다른 답변에서 언급된 바와 같이, 인스턴스(instance) 방법을 사용할 때는 통과시켜야 함self
첫 번째 주장으로서 - 이것이 오류의 원인이다.
뿐만 아니라, 인스턴스(instance) 방법만이 해당 인스턴스를 참조하기 위해 첫 번째 인수로 간주된다는 것을 이해하는 것이 중요하다.
방법이 정적인 경우 통과하지 못함self
, 그러나 acls
대신 논증하다class_
).
아래 예를 참조하십시오.
class City:
country = "USA" # This is a class level attribute which will be shared across all instances (and not created PER instance)
def __init__(self, name, location, population):
self.name = name
self.location = location
self.population = population
# This is an instance method which takes self as the first argument to refer to the instance
def print_population(self, some_nice_sentence_prefix):
print(some_nice_sentence_prefix +" In " +self.name + " lives " +self.population + " people!")
# This is a static (class) method which is marked with the @classmethod attribute
# All class methods must take a class argument as first param. The convention is to name is "cls" but class_ is also ok
@classmethod
def change_country(cls, new_country):
cls.country = new_country
일부 테스트는 상황을 더 명확하게 하기 위한 것이다.
# Populate objects
city1 = City("New York", "East", "18,804,000")
city2 = City("Los Angeles", "West", "10,118,800")
#1) Use the instance method: No need to pass "self" - it is passed as the city1 instance
city1.print_population("Did You Know?") # Prints: Did You Know? In New York lives 18,804,000 people!
#2.A) Use the static method in the object
city2.change_country("Canada")
#2.B) Will be reflected in all objects
print("city1.country=",city1.country) # Prints Canada
print("city2.country=",city2.country) # Prints Canada
매개 변수 no를 지정하지 않은 경우__init__()
또는 다른 방법을 찾는 것.
예를 들면 다음과 같다.
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")
위의 프로그램을 실행하면 다음과 같은 오류가 발생한다.
TypeError: __init__()는 1개의 위치 인수를 사용하지만 6개가 지정됨
이걸 어떻게 제거할 수 있을까?
그냥 매개 변수만 넘기면 돼__init__()
method을 은 방법이다.
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))
수면 부족 시 이 오류가 발생하여 다음 작업을 사용하여 클래스를 만드는 경우def
대신에class
:
def MyClass():
def __init__(self, x):
self.x = x
a = MyClass(3)
-> TypeError: MyClass() takes 0 positional arguments but 1 was given
이야기의 교훈: 수면 부족 상태에서 프로그램을 짜는 것은 지는 싸움이다.
객체를 생성하지 않고 메서드를 호출하려면 메서드를 정적 메서드로 변경하면 된다.
class MyClass:
@staticmethod
def method(arg):
print(arg)
MyClass.method("i am a static method")
클래스를 실제로 생성하십시오.
class accum:
def __init__(self):
self.acc = 0
def accumulator(self, var2add, end):
if not end:
self.acc+=var2add
return self.acc
내 경우, 나는 더하는 것을 잊었다.()
방법을 이렇게 부르고 있었다.
obj = className.myMethod
하지만 이렇게 되어야 한다.
obj = className.myMethod()
통과하다cls
에 대한 매개 변수.@classmethod
이 문제를 해결하기 위해.
@classmethod
def test(cls):
return ''
'Programing' 카테고리의 다른 글
변수가 python 2 및 3과 호환되는 문자열인지 확인하는 방법 (0) | 2022.03.21 |
---|---|
TypeScript에서 조합 유형을 사용하여 배열을 입력하시겠습니까? (0) | 2022.03.21 |
Vue momentjs 타임스탬프에서 실시간으로 상대 시간 업데이트 (0) | 2022.03.21 |
Vue.js에서 생성된 이벤트와 마운트된 이벤트 간의 차이 (0) | 2022.03.21 |
외부 요소 클릭 감지 (0) | 2022.03.21 |