python装饰器和类的装饰器

2019年3月29日00:16:19 发表评论 1,011 views
def func(f1):
    def func1():
        print('ssssss')
        f1()
    def func2():
        print('ddddddd')
        f1()
    return func2

@func
def f1():
    print('基础函数')
f1()


#类的三个内置装饰器
class Base():
    def __init__(self,name):
        self.name = name
    age = 18
    @property#和访问属性一样
    def eat(self):
        print('正在吃东西')
    @staticmethod#设置静态类,和类断开连接
    def run():
        print('正在跑步')
    @classmethod#设置类方法,cls代表类本身,可以直接调用类方法,self是实例方法
    def work(cls):
        print('正在写作业')
        print(cls.age)
        print(cls)
a = Base('优秀')
print(a.age)
a.eat
a.run()
a.work()


结果:
ddddddd
基础函数
18
正在吃东西
正在跑步
正在写作业
18
<class '__main__.Base'>

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: