Skip to content

Instantly share code, notes, and snippets.

@happysundar
Created March 5, 2014 07:24
Show Gist options
  • Save happysundar/9362685 to your computer and use it in GitHub Desktop.
Save happysundar/9362685 to your computer and use it in GitHub Desktop.
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 :

╭ ➜ [email protected]:~/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:

╭ ➜ [email protected]:~/Desktop  
╰ ➤ python ./test.py
A
B
C
A1
B1
C1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment