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

學無先后,達者為師

網站首頁 編程語言 正文

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

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

前言

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

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

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

用函數裝飾函數

采用一個函數定義裝飾器:

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

然后作用在一個函數上:

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

測試一下效果:

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

用函數裝飾一個類

這里通過裝飾器實現單例模式:

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

于是,當你定義多個對象時,返回的是同一實例:

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

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

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

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

再作用在一個函數上:

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

主要是在類中實現__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

小結

學習類裝飾,對Python的內部機制會有更多的了解。如__init__, call, __new__等內置方法。

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

欄目分類
最近更新