日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學(xué)無先后,達(dá)者為師

網(wǎng)站首頁 編程語言 正文

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

作者:北極象 ? 更新時(shí)間: 2022-12-24 編程語言

前言

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

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

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

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

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

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

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

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

測試一下效果:

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

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

這里通過裝飾器實(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)你定義多個(gè)對(duì)象時(shí),返回的是同一實(shí)例:

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

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

先采用類定義一個(gè)裝飾器:

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

再作用在一個(gè)函數(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))

用類定義裝飾器,然后裝飾一個(gè)類

先定義裝飾器:

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

該裝飾器給被裝飾的類上添加了一個(gè)方法,名稱為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í)類裝飾,對(duì)Python的內(nèi)部機(jī)制會(huì)有更多的了解。如__init__, call, __new__等內(nèi)置方法。

原文鏈接:https://blog.csdn.net/jgku/article/details/128020535

欄目分類
最近更新