>  기사  >  백엔드 개발  >  Python 클래스 메소드와 일반 메소드의 차이점

Python 클래스 메소드와 일반 메소드의 차이점

藏色散人
藏色散人원래의
2019-07-03 09:45:033793검색

Python 클래스 메소드와 일반 메소드의 차이점

파이썬 클래스 메서드와 일반 메서드의 차이점

다음에서는 예를 사용하여 차이점을 보여줍니다.

먼저 클래스를 정의합니다. 2가지 메서드가 포함됩니다.

class Apple(object):
        def get_apple(self, n):
                print "apple: %s,%s" % (self,n)
        @classmethod
        def get_class_apple(cls, n):
                print "apple: %s,%s" % (cls,n)

클래스의 공통 메서드

클래스의 공통 메서드는 클래스의 인스턴스에서 호출되어야 합니다.

a = Apple()
a.get_apple(2)

출력 결과

apple: <__main__.Apple object at 0x7fa3a9202ed0>,2

결합 관계를 살펴보세요:

print (a.get_apple)
<bound method Apple.get_apple of <__main__.Apple object at 0x7fa3a9202ed0>>

클래스의 일반적인 메소드는 클래스의 인스턴스에만 사용할 수 있습니다. 클래스를 사용하여 일반 메서드를 호출하면 다음 오류가 발생합니다.

Apple.get_apple(2)
Traceback (most recent call last): File "static.py", line 22, in <module> Apple.get_apple(2) TypeError: unbound method get_apple() must be called with Apple instance as first argument (got int instance instead)

Class method

Class 메서드, 이는 메서드가 클래스에 바인딩되었음을 나타냅니다.

a.get_class_apple(3)
Apple.get_class_apple(3)
apple: <class &#39;__main__.Apple&#39;>,3
apple: <class &#39;__main__.Apple&#39;>,3

바인딩 관계를 다시 살펴보세요:

print (a.get_class_apple) print (Apple.get_class_apple)

인스턴스를 사용할 때와 클래스를 사용하여 호출할 때 출력 결과는 동일합니다.

<bound method type.get_class_apple of <class &#39;__main__.Apple&#39;>> <bound method type.get_class_apple of <class &#39;__main__.Apple&#39;>>

관련 추천: "Python Tutorial"

위 내용은 Python 클래스 메소드와 일반 메소드의 차이점의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.