ProgramingTip

클래스 메서드를 호출하면 Python에서 TypeError가 발생합니다.

bestdevel 2020. 10. 29. 08:23
반응형

클래스 메서드를 호출하면 Python에서 TypeError가 발생합니다.


어떻게 사용하는지 모르겠습니다. 다음 코드는 클래스를 사용하려고 할 때 오류를 제공합니다.

class MyStuff:
    def average(a, b, c): # Get the average of three numbers
        result = a + b + c
        result = result / 3
        return result

# Now use the function `average` from the `MyStuff` class
print(MyStuff.average(9, 18, 27))

오류 :

File "class.py", line 7, in <module>
    print(MyStuff.average(9, 18, 27))
TypeError: unbound method average() must be called with MyStuff instance as first argument (got int instance instead)

뭐가 문제 야?


변수를 선언하고 함수 인 것처럼 클래스를 호출하여 클래스를 인스턴스화 할 수 있습니다.

x = mystuff()
print x.average(9,18,27)

그러나 이것은 우리에게 제공 한 코드 작동하지 않습니다. 주어진 클래스에서 클래스 메서드를 호출하면 함수를 호출 할 때 항상 호출에 대한 포인터를 첫 번째 매개 변수로 전달합니다. 따라서 지금 코드를 실행하면 다음 오류 메시지가 표시됩니다.

TypeError: average() takes exactly 3 arguments (4 given)

이 문제를 해결하려는 경우 4 개의 매개 변수를 사용하는 평균 방법의 정의를 수정해야합니다. 첫 번째 매개 변수는 객체 참조이고 나머지 3 개 매개 변수는 3 개의 숫자에 대한 것입니다.


귀하의 예에서 정적 방법을 사용하고 싶은 것입니다.

class mystuff:
  @staticmethod
  def average(a,b,c): #get the average of three numbers
    result=a+b+c
    result=result/3
    return result

print mystuff.average(9,18,27)

정적에서 정적 메소드를 많이 사용하는 것은 일반적으로 악취의 증상입니다. 실제로 함수가 필요한 경우 모듈 수준에서 직접 선언하십시오.


예제를 최소한으로 수정하려는 코드를 다음과 같이 할 수 있습니다.

class myclass(object):
        def __init__(self): # this method creates the class object.
                pass

        def average(self,a,b,c): #get the average of three numbers
                result=a+b+c
                result=result/3
                return result


mystuff=myclass()  # by default the __init__ method is then called.      
print mystuff.average(a,b,c)

또는 더 완전히 확장하여 다른 방법을 추가 할 수 있습니다.

class myclass(object):
        def __init__(self,a,b,c):
                self.a=a
                self.b=b
                self.c=c
        def average(self): #get the average of three numbers
                result=self.a+self.b+self.c
                result=result/3
                return result

a=9
b=18
c=27
mystuff=myclass(a, b, c)        
print mystuff.average()

클래스 내의 모든 함수와 모든 클래스 변수는 지시 된대로 자기 인수를 가져옵니다 .

class mystuff:
    def average(a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result
    def sum(self,a,b):
            return a+b


print mystuff.average(9,18,27) # should raise error
print mystuff.sum(18,27) # should be ok

클래스 변수가 관련된 경우 :

 class mystuff:
    def setVariables(self,a,b):
            self.x = a
            self.y = b
            return a+b
    def mult(self):
            return x * y  # This line will raise an error
    def sum(self):
            return self.x + self.y

 print mystuff.setVariables(9,18) # Setting mystuff.x and mystuff.y
 print mystuff.mult() # should raise error
 print mystuff.sum()  # should be ok

수업 지향 프로그래밍의 몇 가지 기본 사항에 조금 더 많은 시간을 할애해야합니다.

가혹하게 들리지만 중요합니다.

  • 클래스 정의가하지만 구문은 허용됩니다. 정의가 잘못되었습니다.

  • 클래스를 생성하기 위해 사용이 완전히 제거되었습니다.

  • 계산을 위해 수업을 사용하는 것은 부적절합니다. 이러한 종류의 작업을 수행 할 수 있지만 @staticmehod.

예제 코드가 여러면에서 잘못 되었기 때문에 깔끔한 "이 문제 해결"답변을 얻을 수 없습니다. 고칠 것이 너무 많습니다.

클래스 정의의 더 나은 예를 살펴보아야합니다. 배우기 위해 어떤 소스 자료를 사용하고 있는지는 확실하지 않지만 읽고있는 책이 잘못되었거나 불완전합니다.

사용중인 책이나 출처를 버리고 더 나은 책을 찾으십시오. 진지하게. 그들은 클래스 정의의 모양과 사용 방법에 대해 오해했습니다.

http://homepage.mac.com/s_lott/books/nonprog/htmlchunks/pt11.html 에서 클래스, 객체 및 Python에 대한 더 나은 소개 를 볼 수 있습니다 .


파이썬에서 클래스의 멤버 함수에는 명시 적 self인수 가 필요합니다 . thisC ++의 암시 적 포인터 와 동일합니다 . 자세한 내용은 페이지 를 확인 하십시오.


이 시도:

class mystuff:
    def average(_,a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result

#now use the function average from the mystuff class
print mystuff.average(9,18,27)

아니면 이거:

class mystuff:
    def average(self,a,b,c): #get the average of three numbers
            result=a+b+c
            result=result/3
            return result

#now use the function average from the mystuff class
print mystuff.average(9,18,27)

인스턴스를 만들지 않았습니다.

평균을 인스턴스 메서드로 정의 했으므로 평균을 사용하려면 먼저 인스턴스를 만들어야합니다.

참고 URL : https://stackoverflow.com/questions/396856/calling-a-class-method-raises-a-typeerror-in-python

반응형