happysundar
3/5/2014 - 7:24 AM

classmethod vs staticmethod in python

classmethod vs staticmethod in python

@staticmethod vs @classmethod

If you intend to refer to class variables within a @staticmethod, then you end up using the actual name of the enclosing class. This makes the method un-inheritable only in the cases you refer to the class variables, and the variables happen to be overriden in the subclass - it can still be called from the derived class / derived class instance. In other words, @staticmethods may not behave like proper, polymorphic methods when class variables are overridden.

class Base(object):
    class_vars = ['A','B','C']
    
    @staticmethod
    def test_static():
        for ch in Base.class_vars:
            print ch


class Derived(Base):
    class_vars = ['A1','B1','C1']
    

if __name__ == '__main__':
    Base.test_static()
    Derived.test_static()

will print :

╭ ➜ sundar@Sundars-MacBook-Pro.local:~/Desktop  
╰ ➤ python ./test.py 
A
B
C
A
B
C

Where as:

class Base(object):
    class_vars = ['A','B','C']
    
    @classmethod
    def test_static(cls):
        for ch in cls.class_vars:
            print ch


class Derived(Base):
    class_vars = ['A1','B1','C1']
    

if __name__ == '__main__':
    Base.test_static()
    Derived.test_static()

Will print:

╭ ➜ sundar@Sundars-MacBook-Pro.local:~/Desktop  
╰ ➤ python ./test.py
A
B
C
A1
B1
C1