Python装饰器管理类和函数

发布时间:2024年01月13日

1 Python装饰器管理类和函数

Python装饰器可以管理函数和实例的调用,也可以直接管理函数和类本身。

1.1 装饰器将函数和类保存到字典

描述

通过装饰器将函数或类保存到字典,以便后续使用。

(1) 定义一个字典;

(2) 定义一个装饰器,将装饰的函数或类保存到字典;

(3) 装饰器不调用函数或类,直接返回函数或类;

(4) 通过字典访问保存的函数或类;

示例

>>> registry={}
>>> def register(obj):
    registry[obj.__name__]=obj
    return obj

>>> @register
def testadd(a,b):
    return a+b

>>> @register
def testsub(a,b):
    return a-b
>>> @register
class TestMul:
    def __init__(self,a,b):
        self.mul=a*b
    def __str__(self):
        return str(self.mul)

>>> for k in registry:
    print(k,'->',registry[k],type(registry[k]))

    
testadd -> <function testadd at 0x000001B92C23BAF0> <class 'function'>
testsub -> <function testsub at 0x000001B92C2FC040> <class 'function'>
TestMul -> <class '__main__.TestMul'> <class 'type'>

>>> for k in registry:
    print(k,'=>',registry[k](5,2))

    
testadd => 7
testsub => 3
TestMul => 10

1.2 装饰器为函数添加属性

描述

通过装饰器为装饰函数添加属性,以便后续使用。

(1) 定义一个装饰器;

(2) 为装饰函数添加属性,内部给属性值,或者外部送入属性值;

(3) 返回装饰函数;

(4) 访问装饰器函数添加的属性;

示例

>>> def markdeco(func):
    func.marked=True
    return func

>>> @markdeco
def testmul(a,b):
    return a*b

>>> testmul.marked
True
>>> def myannotate(note):
    def notedeco(func):
        func.lab=note
        return func
    return notedeco
>>> @myannotate('梯阅线条')
def testsub(a,b):
    return a-b

>>> testsub.lab
'梯阅线条'
>>> testsub(5,2)
3
文章来源:https://blog.csdn.net/sinat_34735632/article/details/135576247
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。