Normal method, @staticmethod, @classmethod of python
March 18th, 2009
Reference:
http://snippets.dzone.com/posts/show/1679
http://www.geocities.com/foetsch/python/new_style_classes.htm
Check the doctest in these code bottom.
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test the variable methods in class """ class K(object): """ Test the variable methods in class >>> k_obj = K() >>> k_obj.method1() Normal method: obj.method1() becomes method1(obj) >>> K.method2() classmethod: K.method2() becomes method2(klass: <class '__main__.K'>) >>> k_obj.method2() classmethod: K.method2() becomes method2(klass: <class '__main__.K'>) >>> K.method3() staticmethod: K.method3() become just method3(None) >>> k_obj.method3() staticmethod: K.method3() become just method3(None) """ # normal method (instance method) def method1(self): print 'Normal method: obj.method1() becomes method1(obj)' # class method @classmethod def method2(cls): print 'classmethod: K.method2() becomes method2(klass: %s)' % cls # static method @staticmethod def method3(): print 'staticmethod: K.method3() become just method3(None)' class KK(K): """ Test the variable methods' behavior in the subclass. >>> kk_obj = KK() >>> kk_obj.method1() Normal method: obj.method1() becomes method1(obj) >>> KK.method2() classmethod: K.method2() becomes method2(klass: <class '__main__.KK'>) >>> kk_obj.method2() classmethod: K.method2() becomes method2(klass: <class '__main__.KK'>) >>> KK.method3() staticmethod: K.method3() become just method3(None) >>> kk_obj.method3() staticmethod: K.method3() become just method3(None) """ pass if __name__ == "__main__": import doctest doctest.testmod()
Recent Comments