[Python]Class and Static method

class A(object):
    def foo(self,x):
        print("executing foo(%s,%s)"%(self,x))

    @classmethod
    def class_foo(cls,x):
        print("executing class_foo(%s,%s)"%(cls,x))

    @staticmethod
    def static_foo(x):
        print("executing static_foo(%s)"%x)

a=A()

Let's take a look at what are those functions.

print(a.foo)
#<bound method A.foo of <__main__.A object at 0x0E29AD70>>

print(a.class_foo)
#<bound method A.class_foo of <class '__main__.A'>>

print(A.class_foo)
#<bound method A.class_foo of <class '__main__.A'>>

print(a.static_foo)
#<function A.static_foo at 0x0E2A4F60>

print(A.static_foo)
#<function A.static_foo at 0x0E2A4F60>

foo expects 2 arguments, while a.foo only expects 1 argument. a is bound to foo. That is what is meant by the term "bound".

For a.class_foo, a is not bound to class_foo, rather the class A is bound to class_foo. In fact, if you define something to be a classmethod, it is probably because you intend to call it from the class rather than from a class instance.

One use people have found for class methods is to create inheritable alternative constructors. https://stackoverflow.com/questions/1950414/what-does-classmethod-do-in-this-code/1950927#1950927

Staticmethod a.static_foo just returns a good 'ole function with no arguments bound. static_foo expects 1 argument, and a.static_foo expects 1 argument too. neither self (the object instance) nor cls (the class) is implicitly passed as the first argument. They behave like plain functions except that you can call them from an instance or the class.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容