带有自身参数的类方法装饰器?

2025-02-10 08:57:00
admin
原创
47
摘要:问题描述:如何将类字段作为参数传递给类方法上的装饰器?我想要做的事情如下:class Client(object): def __init__(self, url): self.url = url @check_authorization("some_attr&qu...

问题描述:

如何将类字段作为参数传递给类方法上的装饰器?我想要做的事情如下:

class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization("some_attr", self.url)
    def get(self):
        do_work()

它抱怨说 self 不存在,无法传递self.url给装饰器。有办法解决这个问题吗?


解决方案 1:

是的。不要在类定义时传递实例属性,而是在运行时检查它:

def check_authorization(f):
    def wrapper(*args):
        print args[0].url
        return f(*args)
    return wrapper

class Client(object):
    def __init__(self, url):
        self.url = url

    @check_authorization
    def get(self):
        print 'get'

>>> Client('http://www.google.com').get()
http://www.google.com
get

装饰器会拦截方法参数;第一个参数是实例,因此它会从中读取属性。您可以将属性名称作为字符串传递给装饰器,getattr如果您不想对属性名称进行硬编码,请使用:

def check_authorization(attribute):
    def _check_authorization(f):
        def wrapper(self, *args):
            print getattr(self, attribute)
            return f(self, *args)
        return wrapper
    return _check_authorization

解决方案 2:

更简洁的例子可能如下:

#/usr/bin/env python3
from functools import wraps

def wrapper(method):
    @wraps(method)
    def _impl(self, *method_args, **method_kwargs):
        method_output = method(self, *method_args, **method_kwargs)
        return method_output + "!"
    return _impl

class Foo:
    @wrapper
    def bar(self, word):
        return word

f = Foo()
result = f.bar("kitty")
print(result)

这将打印:

kitty!

解决方案 3:

from re import search
from functools import wraps

def is_match(_lambda, pattern):
    def wrapper(f):
        @wraps(f)
        def wrapped(self, *f_args, **f_kwargs):
            if callable(_lambda) and search(pattern, (_lambda(self) or '')): 
                f(self, *f_args, **f_kwargs)
        return wrapped
    return wrapper

class MyTest(object):

    def __init__(self):
        self.name = 'foo'
        self.surname = 'bar'

    @is_match(lambda x: x.name, 'foo')
    @is_match(lambda x: x.surname, 'foo')
    def my_rule(self):
        print 'my_rule : ok'

    @is_match(lambda x: x.name, 'foo')
    @is_match(lambda x: x.surname, 'bar')
    def my_rule2(self):
        print 'my_rule2 : ok'



test = MyTest()
test.my_rule()
test.my_rule2()

输出:my_rule2:ok

解决方案 4:

另一种选择是放弃语法糖并在__init__类中进行装饰。

def countdown(number):
    def countdown_decorator(func):
        def func_wrapper():
            for index in reversed(range(1, number+1)):
                print(index)
            func()
        return func_wrapper
    return countdown_decorator

class MySuperClass():
    def __init__(self, number):
        self.number = number
        self.do_thing = countdown(number)(self.do_thing)
    
    def do_thing(self):
        print('im doing stuff!')


myclass = MySuperClass(3)

myclass.do_thing()

这将打印

3
2
1
im doing stuff!

解决方案 5:

我知道这个问题已经存在很久了,但下面的解决方法之前还没有被提出过。这里的问题是你不能self在类块中访问,但你可以在类方法中访问。

让我们创建一个虚拟装饰器来重复执行某个函数几次。

import functools
def repeat(num_rep):
    def decorator_repeat(func):
        @functools.wraps(func)
        def wrapper_repeat(*args, **kwargs):
            for _ in range(num_rep):
                value = func(*args, **kwargs)
            return 
        return wrapper_repeat
    return decorator_repeat
class A:
    def __init__(self, times, name):
        self.times = times
        self.name = name
    
    def get_name(self):
        @repeat(num_rep=self.times)
        def _get_name():
            print(f'Hi {self.name}')
        _get_name()

解决方案 6:

我知道这是一个老问题,但这个解决方案还没有被提及,希望它甚至可以在 8 年后的今天帮助到某些人。

那么,包装包装器怎么样?假设不能更改装饰器,也不能装饰init中的那些方法(它们可能是 @property 装饰的或其他什么)。总是有可能创建自定义的、特定于类的装饰器,它将捕获自身并随后调用原始装饰器,并将运行时属性传递给它。

这是一个有效的例子(f 字符串需要 python 3.6):

import functools

# imagine this is at some different place and cannot be changed
def check_authorization(some_attr, url):
        def decorator(func):
                @functools.wraps(func)
                def wrapper(*args, **kwargs):
                        print(f"checking authorization for '{url}'...")
                        return func(*args, **kwargs)
                return wrapper
        return decorator

# another dummy function to make the example work
def do_work():
        print("work is done...")

###################
# wrapped wrapper #
###################
def custom_check_authorization(some_attr):
        def decorator(func):
                # assuming this will be used only on this particular class
                @functools.wraps(func)
                def wrapper(self, *args, **kwargs):
                        # get url
                        url = self.url
                        # decorate function with original decorator, pass url
                        return check_authorization(some_attr, url)(func)(self, *args, **kwargs)
                return wrapper
        return decorator
        
#############################
# original example, updated #
#############################
class Client(object):
        def __init__(self, url):
                self.url = url
    
        @custom_check_authorization("some_attr")
        def get(self):
                do_work()

# create object
client = Client(r"https://stackoverflow.com/questions/11731136/class-method-decorator-with-self-arguments")

# call decorated function
client.get()

输出:

checking authorisation for 'https://stackoverflow.com/questions/11731136/class-method-decorator-with-self-arguments'...
work is done...

解决方案 7:

不能。self类主体中没有,因为不存在实例。您需要传递它,例如,str包含要在实例上查找的属性名称,然后返回的函数可以执行此操作,或者使用完全不同的方法。

解决方案 8:

拥有一个通用实用程序将非常有用,它可以将任何函数装饰器转换为方法装饰器。我想了一个小时,终于想出了一个:

from typing import Callable
Decorator = Callable[[Callable], Callable]

def decorate_method(dec_for_function: Decorator) -> Decorator:

    def dec_for_method(unbounded_method) -> Callable:
        # here, `unbounded_method` will be a unbounded function, whose
        # invokation must have its first arg as a valid `self`. When it 
        # return, it also must return an unbounded method.
        def decorated_unbounded_method(self, *args, **kwargs):
            @dec_for_function
            def bounded_method(*args, **kwargs):
                return unbounded_method(self, *args, **kwargs)
            return bounded_method(*args, **kwargs)

        return decorated_unbounded_method

    return dec_for_method

用法是:

# for any decorator (with or without arguments)
@some_decorator_with_arguments(1, 2, 3)
def xyz(...): ...

# use it on a method:
class ABC:
  @decorate_method(some_decorator_with_arguments(1, 2, 3))
  def xyz(self, ...): ...

测试:

def dec_for_add(fn):
    """This decorator expects a function: (x,y) -> int.

    If you use it on a method (self, x, y) -> int, it will fail at runtime.
    """
    print(f"decorating: {fn}")
    def add_fn(x,y):
        print(f"Adding {x} + {y} by using {fn}")
        return fn(x,y)
    return add_fn


@dec_for_add
def add(x,y):
    return x+y

add(1,2)  # OK!


class A:
    @dec_for_add
    def f(self, x, y):
        # ensure `self` is still a valid instance
        assert isinstance(self, A)
        return x+y

# TypeError: add_fn() takes 2 positional arguments but 3 were given
# A().f(1,2)
    

class A:
    @decorate_method(dec_for_add)
    def f(self, x, y):
        # ensure `self` is still a valid instance
        assert isinstance(self, A)
        return x+y

# Now works!!
A().f(1,2)

解决方案 9:

您可以使用带有包装器函数的装饰器,当包装器作为绑定方法被调用时,该装饰器会动态地装饰给定的方法,此时包装器self变为可用。

这个想法可以推广为高阶装饰器with_self,它将动作函数(my_check_authorization在下面的例子中)转换为方法包装装饰器:

def with_self(func):
    def decorator(method):
        def wrapper(self, *args, **kwargs):
            return func(self)(method)(self, *args, **kwargs)
        return wrapper
    return decorator

@with_self
def my_check_authorization(self):
    return check_authorization("some_attr", self.url)

这样您就可以简单地用以下方法装饰您的方法my_check_authorization

class Client(object):
    def __init__(self, url):
        self.url = url

    @my_check_authorization
    def get(self):
        do_work()
相关推荐
  政府信创国产化的10大政策解读一、信创国产化的背景与意义信创国产化,即信息技术应用创新国产化,是当前中国信息技术领域的一个重要发展方向。其核心在于通过自主研发和创新,实现信息技术应用的自主可控,减少对外部技术的依赖,并规避潜在的技术制裁和风险。随着全球信息技术竞争的加剧,以及某些国家对中国在科技领域的打压,信创国产化显...
工程项目管理   1565  
  为什么项目管理通常仍然耗时且低效?您是否还在反复更新电子表格、淹没在便利贴中并参加每周更新会议?这确实是耗费时间和精力。借助软件工具的帮助,您可以一目了然地全面了解您的项目。如今,国内外有足够多优秀的项目管理软件可以帮助您掌控每个项目。什么是项目管理软件?项目管理软件是广泛行业用于项目规划、资源分配和调度的软件。它使项...
项目管理软件   1354  
  信创国产芯片作为信息技术创新的核心领域,对于推动国家自主可控生态建设具有至关重要的意义。在全球科技竞争日益激烈的背景下,实现信息技术的自主可控,摆脱对国外技术的依赖,已成为保障国家信息安全和产业可持续发展的关键。国产芯片作为信创产业的基石,其发展水平直接影响着整个信创生态的构建与完善。通过不断提升国产芯片的技术实力、产...
国产信创系统   21  
  信创生态建设旨在实现信息技术领域的自主创新和安全可控,涵盖了从硬件到软件的全产业链。随着数字化转型的加速,信创生态建设的重要性日益凸显,它不仅关乎国家的信息安全,更是推动产业升级和经济高质量发展的关键力量。然而,在推进信创生态建设的过程中,面临着诸多复杂且严峻的挑战,需要深入剖析并寻找切实可行的解决方案。技术创新难题技...
信创操作系统   27  
  信创产业作为国家信息技术创新发展的重要领域,对于保障国家信息安全、推动产业升级具有关键意义。而国产芯片作为信创产业的核心基石,其研发进展备受关注。在信创国产芯片的研发征程中,面临着诸多复杂且艰巨的难点,这些难点犹如一道道关卡,阻碍着国产芯片的快速发展。然而,科研人员和相关企业并未退缩,积极探索并提出了一系列切实可行的解...
国产化替代产品目录   28  
热门文章
项目管理软件有哪些?
云禅道AD
禅道项目管理软件

云端的项目管理软件

尊享禅道项目软件收费版功能

无需维护,随时随地协同办公

内置subversion和git源码管理

每天备份,随时转为私有部署

免费试用