Python装饰器

空扰寡人 提交于 2019-11-30 19:56:17
# class WithoutDecorators:
#     def some_static_method():
#         print('this is a static method')
#     some_static_method = staticmethod(some_static_method)

#     def some_class_method(cls):
#         print('this is a class method')
    
#     some_class_method = classmethod(some_class_method)


# WithoutDecorators.some_class_method() 
# WithoutDecorators.some_static_method() 


#类的静态方法申明(装饰模式))
class WithoutDecorators:
    def foo(self):
        print('foo')

    @staticmethod
    def some_static_method():
        print('this is a some_static_method')
        WithoutDecorators.foo(WithoutDecorators()) #静态方法在调用类的非静态方法时候需要实例化类本身
                                                   #因此静态方法申明尽量只处理单一的与类属性无关的逻辑
    
    @classmethod
    def some_class_method(cls):
        print('this is a some_class_method')
        cls().foo()           #静态类方法调用本身利用cls指针去调用类的非静态方法

WithoutDecorators.some_static_method()
WithoutDecorators.some_class_method()输出结果:

this is a some_static_method
foo
this is a some_class_method
foo

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!