最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Python裝飾器的四種定義形式

 更新時間:2022年11月26日 16:11:55   作者:北極象  
裝飾器(decorator)在Python框架中扮演著重要角色,是Python中實(shí)現(xiàn)切面編程(AOP)的重要手段,這篇文章主要介紹了Python裝飾器的四種定義形式,需要的朋友可以參考下

前言

裝飾器(decorator)在Python框架中扮演著重要角色,是Python中實(shí)現(xiàn)切面編程(AOP)的重要手段。

aspect-oriented programming (AOP) ,在不改變代碼自身的前提下增加程序功能

不改變代碼自身,但需要在函數(shù)和類頭上加一個標(biāo)注(annotation),這個標(biāo)注在Python里叫裝飾器,在java里叫注解。
在Python里,一共有四種組合形式。下面一一舉例。

用函數(shù)裝飾函數(shù)

采用一個函數(shù)定義裝飾器:

def decorate(f):
    def wrapper(*args):
        return f(*args)*2
    return wrapper

然后作用在一個函數(shù)上:

@decorate
def add(a, b):
	return a + b

測試一下效果:

def test_decorate():
	sum = add(3, 5)
	assert sum == 16

用函數(shù)裝飾一個類

這里通過裝飾器實(shí)現(xiàn)單例模式:

def singleton(cls):
    instances = {}
    def wrapper(*args, **kwargs):
        if cls not in instances:
          instances[cls] = cls(*args, **kwargs)
        return instances[cls]
    return wrapper

使用該裝飾器:

@singleton
class MyClass:
    def method(self):
        pass

于是,當(dāng)你定義多個對象時,返回的是同一實(shí)例:

obj = MyClass()  # creates a new instance
obj2 = MyClass()  # returns the same instance
obj3 = MyClass()  # returns the same instance
...

用類定義裝飾器,然后裝飾一個函數(shù)

先采用類定義一個裝飾器:

class Star:
    def __init__(self, n):
        self.n = n

    def __call__(self, fn):
        @wraps(fn)
        def wrapper(*args, **kwargs):
            result = fn(*args, **kwargs)
            return result
        return wrapper

再作用在一個函數(shù)上:

@Star(5)
def add(a, b):
    return a + b

主要是在類中實(shí)現(xiàn)__call__方法。上面例子也可以簡化:

class MyDecorator:
    def __init__(self, function):
        self.function = function
     
    def __call__(self, *args, **kwargs):
 
        # We can add some code
        # before function call
 
        self.function(*args, **kwargs)
 
        # We can also add some code
        # after function call.
# adding class decorator to the function
@MyDecorator
def function(name, message ='Hello'):
    print("{}, {}".format(message, name))

用類定義裝飾器,然后裝飾一個類

先定義裝飾器:

class MyClassDecorator(object):
	_instances = dict()

	def __init__(self, name):
		pass

	def __call__(self, cls):
		class WrappedClass(cls):
			def say_hello(self):
				print(f'Hello: {self.username}')
		return WrappedClass

該裝飾器給被裝飾的類上添加了一個方法,名稱為say_hello()。使用如下:

@MyClassDecorator('test')
class MyClass():
	def __init__(self, username):
		self.username = username

然后:

def test_decoratorforclass():
	obj = MyClass('user1')
	obj.say_hello()

打印出: Hello: user1

小結(jié)

學(xué)習(xí)類裝飾,對Python的內(nèi)部機(jī)制會有更多的了解。如__init__, call, __new__等內(nèi)置方法。

到此這篇關(guān)于Python裝飾器的四種定義形式的文章就介紹到這了,更多相關(guān)Python裝飾器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論

泾源县| 安宁市| 合阳县| 长沙市| 谷城县| 安乡县| 韩城市| 玛曲县| 麻栗坡县| 宜兴市| 尚志市| 介休市| 孟州市| 汝城县| 常熟市| 吉安县| 宁南县| 洞口县| 哈尔滨市| 肥西县| 洞口县| 历史| 新河县| 沙湾县| 黎川县| 富源县| 游戏| 蕲春县| 札达县| 清水河县| 沛县| 凤山县| 广西| 比如县| 禄劝| 台江县| 磴口县| 河东区| 敦化市| 无锡市| 玛多县|