Skip to content

Instantly share code, notes, and snippets.

@thomas-mangin
Created July 9, 2015 16:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomas-mangin/f3ba31e1bad1a358be73 to your computer and use it in GitHub Desktop.
Save thomas-mangin/f3ba31e1bad1a358be73 to your computer and use it in GitHub Desktop.
staticmethod vs classmethod
import time
def nop_function ():
pass
def access_function ():
local = Test.scoped_value
class Test (object):
scoped_value = 1
@staticmethod
def nop_class_static ():
pass
@classmethod
def nop_class_method (cls):
pass
def nop_class_function (self):
pass
#
@classmethod
def access_class_method (cls):
local = cls.scoped_value
def access_class_function (self):
local = self.scoped_value
def timer (function,loop=10000000):
start = time.time()
for _ in range(loop):
function()
end = time.time()
print 'function %s took %f' % (function.__name__,end-start)
test = Test()
# class creation time
timer(Test)
# class access time
timer(nop_function)
print
timer(Test.nop_class_static)
timer(Test.nop_class_method)
timer(test.nop_class_function)
print
timer(access_function)
timer(Test.access_class_method)
timer(test.access_class_function)
print
@xiaopeng163
Copy link

yes, you just count create class time once. but if there is a need to create class instance each time, then classmethod is better, yes?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment