programing

"TypeError: method()는 1개의 positional 인수를 사용하지만 2개의 positional 인수가 지정되었습니다." 그러나 1개만 통과했습니다.

muds 2023. 4. 16. 15:55
반응형

"TypeError: method()는 1개의 positional 인수를 사용하지만 2개의 positional 인수가 지정되었습니다." 그러나 1개만 통과했습니다.

수업이 있으면...

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)

...이 경우 추가는 필요 없습니다.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도 마찬가지)

물론 이것은 "파라미터가 필요 없는" 타입 에러입니다.Python에서의 오브젝트 초기화에 관해서는, 1개를 예상했을 때의 "2개"와 크게 다르지 않습니다.

토픽에 대한 대응:구문적으로 올바른 경우 오버로드 이니셜라이저가 사용되지만 그렇지 않은 경우 무시되고 대신 삽입된 이니셜라이저가 사용됩니다.오브젝트는 이것을 예상/처리하지 않고 에러가 발생합니다.

systax 오류의 경우:수정은 간단합니다.custom init 문을 편집하기만 하면 됩니다.

def __init__(self, name):
    self.name = name

문제는 키워드 인수를 함수에 올바르게 전달하지 못한 경우에도 발생할 수 있습니다.

예를 들어 다음과 같이 정의된 메서드가 있습니다.

def create_properties_frame(self, parent, **kwargs):

다음과 같은 호출:

self.create_properties_frame(frame, kw_gsp)

이 되다TypeError: create_properties_frame() takes 2 positional arguments but 3 were given「」이 있기 때문에kw_gsp사전은 별도의 키워드 인수로 압축 해제되지 않고 위치 인수로 취급됩니다.

해결책은 다음과 같이 추가하는 것입니다.** 설명:

self.create_properties_frame(frame, **kw_gsp)

했듯이 사례 할 때는 .self첫 번째 인수로 - 이것이 오류의 원인입니다.

또한 인스턴스를 참조하기 위해서는 인스턴스 메서드만이 첫 번째 인수로 사용됨을 이해하는 것이 중요합니다.

방법이 Static인 경우 합격하지 않습니다.self ,,cls인수( 인수)를 지정합니다.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

때 합니다.__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__() takes 1 positional argument but 6 were given

이걸 어떻게 없애지?

.무엇이 좋을까요?__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))

오브젝트를 작성하지 않고 메서드를 호출하는 경우 메서드를 스태틱메서드로 변경할 수 있습니다.

class MyClass:

    @staticmethod
    def method(arg):
        print(arg)

MyClass.method("i am a static method")

때 이하는데, 이 오류는 '수면 부족'을 사용해서 .defclass:

def MyClass():
    def __init__(self, x):
        self.x = x

a = MyClass(3)
-> TypeError: MyClass() takes 0 positional arguments but 1 was given

실제로 클래스를 만들어야 합니다.

class accum:
    def __init__(self):
        self.acc = 0
    def accumulator(self, var2add, end):
        if not end:
            self.acc+=var2add
        return self.acc

만약 당신이 장고를 경험한다면, 이것은 다음과 같은 것을 의미합니다.

  1. 오브젝트를 함수에 추가하면 Django는 나머지를 이해하게 됩니다.예:
def display_genre(self, obj):
        return ', '.join(genre.name for genre in obj.genre.all())}

제, 가, 가를 붙이는 .()

나는 이 방법을 이렇게 부르고 있었다.

obj = className.myMethod

하지만 이렇게 해야 한다.

obj = className.myMethod()

언급URL : https://stackoverflow.com/questions/23944657/typeerror-method-takes-1-positional-argument-but-2-were-given-but-i-only-pa

반응형