码迷,mamicode.com
首页 > 编程语言 > 详细

Python装饰器

时间:2019-10-09 00:07:21      阅读:78      评论:0      收藏:0      [点我收藏+]

标签:非静态方法   static   ati   静态方法   some   装饰模式   @class   def   tde   

# 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

Python装饰器

标签:非静态方法   static   ati   静态方法   some   装饰模式   @class   def   tde   

原文地址:https://www.cnblogs.com/ms_senda/p/11638519.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!