Program Tip

언제 @classmethod를 사용해야하고 언제 def method (self)를 사용해야합니까?

programtip 2020. 11. 2. 08:22
반응형

언제 @classmethod를 사용해야하고 언제 def method (self)를 사용해야합니까?


전에 사용하지 않은 Django 앱을 통합하는 동안 클래스에서 함수를 정의하는 데 사용되는 두 가지 다른 방법을 발견했습니다. 저자는 둘 다 매우 의도적으로 사용하는 것 같습니다. 첫 번째는 내가 많이 사용하는 것입니다.

class Dummy(object):

    def some_function(self,*args,**kwargs):
        do something here
        self is the class instance

다른 하나는 내가 사용하지 않는 것입니다. 주로 사용시기와 용도를 이해하지 못하기 때문입니다.

class Dummy(object):

    @classmethod
    def some_function(cls,*args,**kwargs):
        do something here
        cls refers to what?

Python 문서에서 classmethod데코레이터는 다음 문장으로 설명됩니다.

클래스 메서드는 인스턴스 메서드가 인스턴스를받는 것처럼 클래스를 암시 적 첫 번째 인수로받습니다.

그래서 나는 자신을 cls참조한다고 생각 Dummy합니다 ( class인스턴스가 아니라). 나는 항상 이것을 할 수 있기 때문에 이것이 왜 존재하는지 정확히 이해하지 못합니다.

type(self).do_something_with_the_class

이것은 단지 명확성을위한 것일까 요, 아니면 제가 가장 중요한 부분을 놓쳤나요 : 그것 없이는 할 수 없었던 으스스하고 매혹적인 일들을 놓쳤나요?


당신의 추측은 정확합니다-당신은 작동 방식 을 이해 합니다classmethod .

그 이유는 이러한 메서드가 인스턴스 또는 클래스 모두에서 호출 될 수 있기 때문입니다 (두 경우 모두 클래스 개체가 첫 번째 인수로 전달됨).

class Dummy(object):

    @classmethod
    def some_function(cls,*args,**kwargs):
        print cls

#both of these will have exactly the same effect
Dummy.some_function()
Dummy().some_function()

인스턴스에서 이들의 사용 : 인스턴스에서 클래스 메서드를 호출하는 데 적어도 두 가지 주요 용도가 있습니다.

  1. self.some_function()해당 호출이 발생하는 클래스가 아닌 some_function의 실제 유형에서 의 버전 self을 호출합니다 (클래스 이름이 변경되면주의 할 필요가 없습니다).
  2. 경우에 어디에 some_function어떤 프로토콜을 구현하는 것이 필요하다, 그러나 혼자 클래스 객체를에 전화를하는 데 유용합니다.

차이점staticmethod : 인스턴스 데이터에 액세스하지 않는 메서드를 정의하는 또 다른 방법이 staticmethod있습니다. 이는 암시 적 첫 번째 인수를 전혀받지 않는 메서드를 생성합니다. 따라서 호출 된 인스턴스 또는 클래스에 대한 정보는 전달되지 않습니다.

In [6]: class Foo(object): some_static = staticmethod(lambda x: x+1)

In [7]: Foo.some_static(1)
Out[7]: 2

In [8]: Foo().some_static(1)
Out[8]: 2

In [9]: class Bar(Foo): some_static = staticmethod(lambda x: x*2)

In [10]: Bar.some_static(1)
Out[10]: 2

In [11]: Bar().some_static(1)
Out[11]: 2

내가 찾은 주요 용도는 기존 함수 (를받을 것으로 예상하지 않음 self)를 클래스 (또는 객체)의 메서드로 조정하는 것입니다.


If you add decorator @classmethod, That means you are going to make that method as static method of java or C++. ( static method is a general term I guess ;) ) Python also has @staticmethod. and difference between classmethod and staticmethod is whether you can access to class or static variable using argument or classname itself.

class TestMethod(object):
    cls_var = 1
    @classmethod
    def class_method(cls):
        cls.cls_var += 1
        print cls.cls_var

    @staticmethod
    def static_method():
        TestMethod.cls_var += 1
        print TestMethod.cls_var
#call each method from class itself.
TestMethod.class_method()
TestMethod.static_method()

#construct instances
testMethodInst1 = TestMethod()    
testMethodInst2 = TestMethod()   

#call each method from instances
testMethodInst1.class_method()
testMethodInst2.static_method()

all those classes increase cls.cls_var by 1 and print it.

And every classes using same name on same scope or instances constructed with these class is going to share those methods. There's only one TestMethod.cls_var and also there's only one TestMethod.class_method() , TestMethod.static_method()

And important question. why these method would be needed.

classmethod or staticmethod is useful when you make that class as a factory or when you have to initialize your class only once. like open file once, and using feed method to read the file line by line.

참고URL : https://stackoverflow.com/questions/10586787/when-should-i-use-classmethod-and-when-def-methodself

반응형