When should I use @classmethod and when def method(self)?

前端 未结 3 1223
北恋
北恋 2020-12-02 05:41

While integrating a Django app I have not used before, I found two different ways used to define functions in classes. The author seems to use them both very intentionally.

3条回答
  •  鱼传尺愫
    2020-12-02 06:02

    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.

提交回复
热议问题