Python圈Python基础

Python11--装饰器

2020-08-31  本文已影响0人  伊洛的小屋
1.装饰器定义
2.装饰器简单的例子
#!/usr/bin/python
from datetime import datetime

def release_skills(hero):
    def release_skill(*skill, **skills):
        print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        return hero(*skill, **skills)
    return release_skill


@release_skills
def hero(name, skill):
    return (name + '-->'+'释放技能:'+ skill)


print(hero('关羽', 'fire'))
print(hero.__name__)
(yiluo) ➜  Code python hero.py
2019-12-12 11:11:49
关羽-->释放技能:fire
release_skill
# 作者:伊洛Yiluo 公众号:伊洛的小屋
# 个人主页:https://yiluotalk.com/
# 博客园:https://www.cnblogs.com/yiluotalk/
#!/usr/bin/python
from datetime import datetime
from functools import wraps

def release_skills(hero):
    @wraps(hero)
    def release_skill(*skill, **skills):
        print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        return hero(*skill, **skills)
    return release_skill


@release_skills
def hero(name, skill):
    return (name + '-->'+'释放技能:'+ skill)


print(hero('关羽', 'fire'))
print(hero.__name__)
(yiluo) ➜  Code python hero.py
2019-12-12 11:25:38
关羽-->释放技能:fire
hero
3.property 装饰器
#!/usr/bin/env python3

class Animal:
    def __init__(self):
        self.age = 3


if __name__ == "__main__":
    cat = Animal()
    print(cat.age)
    cat.age = 'age'
    print(cat.age)
➜  code python3 demo.py
3
age
#!/usr/bin/env python3

class Animal:
    def __init__(self):
        self.__age = 3
    def get_age(self):
        return self.__age
    def set_age(self, value):
        if isinstance(value, int):
            self.__age = value
        else:
            raise ValueError


if __name__ == "__main__":
    cat = Animal()
    print(cat.get_age)
    cat.set_age('age')
Traceback (most recent call last):
  File "demo.py", line 18, in <module>
    cat.set_age('age')
  File "demo.py", line 12, in set_age
    raise ValueError
ValueError
#!/usr/bin/env python3

class Animal:
    def __init__(self):
        self.__age = 3
    @property
    def age(self):
        return self.__age
    @age.setter
    def age(self, value):
        if isinstance(value, int):
            self.__age = value
        else:
            raise ValueaError
    @age.deleter
    def age(self):
        print('delete age')
        del self.__age

if __name__ == "__main__":
    cat = Animal()
    print(cat.age)
    cat.age = 6
    print(cat.age)
    del cat.age
    print(cat.age)
➜  code python3 demo.py
3
6
delete age
Traceback (most recent call last):
  File "demo.py", line 26, in <module>
    print(cat.age)
  File "demo.py", line 8, in age
    return self.__age
AttributeError: 'Animal' object has no attribute '_Animal__age'

欢迎下方【戳一下】【点赞】
Author:伊洛Yiluo
愿你享受每一天,Just Enjoy !

上一篇下一篇

猜你喜欢

热点阅读