简体   繁体   English

在python中仅使用一个装饰器使用定义的属性并将n个属性传递给包装器

[英]Use defined attributes and passing n number of attributes to wrapper using only one decorator in python

I am learning to use decorators and I can't figure out how to pass already defined attributes to the wrapper without making a function specific decorator.我正在学习使用装饰器,但我无法弄清楚如何在不制作特定于功能的装饰器的情况下将已定义的属性传递给包装器。

Let's say I have a decorator :假设我有一个装饰器:

def decorator(func):
    def wrapper():
        print("Before the function")
        func()
        print("After the function")

    return wrapper

With this I am only able to use it with functions with only defined attributes or without any attribute like :有了这个,我只能将它与仅具有定义属性或没有任何属性的函数一起使用,例如:

@decorator
def foo1(attribute1=10, attribute2=20):
    print(attribute1, attribute2)
    return

foo1()

But it makes me unable to run :但这让我无法运行:

foo1(1, 2)

With this problem, I also can't use this decorator on different functions that don't have the same amount of attributes to set.对于这个问题,我也不能在没有相同数量的属性设置的不同函数上使用这个装饰器。

So, it there a way to fix this problem without the use of *args and **kwargs or at least without having to call a function that would look like this : foo((arg1, arg2, argn)) ?那么,有没有一种方法可以在不使用*args**kwargs情况下解决这个问题,或者至少不必调用如下所示的函数: foo((arg1, arg2, argn)) Because it would make me unable to define any attribute.因为这会让我无法定义任何属性。 This is my only restrain.这是我唯一的克制。

Thanks.谢谢。

The wrapper has to accept arguments (because it replaces the original function bound to the decorated name), and those arguments have to be passed to func .包装器必须接受参数(因为它替换了绑定到修饰名称的原始函数),并且这些参数必须传递给func

def decorator(func):
    def wrapper(*args, **kwargs):
        print("Before the function")
        func(*args, **kwargs)
        print("After the function")

    return wrapper

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Python中使用类属性通过修饰符修改文档字符串 - Using class attributes to modify a docstring with a decorator in Python Python:只允许设置具有@property 装饰器的属性 - Python: Only allow attributes to be set that have a @property decorator python类属性的全局装饰器 - python global decorator for class attributes Python Decorator也可用于未定义的属性 - Python Decorator also for undefined attributes 如何在 python 中创建装饰器/包装器 class 以将错误日志的属性作为单个参数传递? - how to create a decorator/ wrapper class in python to pass the attributes of error logs as a single parameter? 对 Python 类中的相关属性使用 @property 装饰器 - Using the @property decorator for interrelated attributes within a Python class Python:为什么在装饰器中使用包装器? - python: why use a wrapper in decorator? 如何在python中使用abstractproperty装饰器强制子类来设置属性? - How to enforce a child class to set attributes using abstractproperty decorator in python? 对多个属性使用描述符(编辑:不是单个装饰器)吗? - Use a Descriptor (EDIT: Not a single decorator) for multiple attributes? 使用 Python 元类来限制属性的数量 - Using Python Metaclasses to Limit the Number of Attributes
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM