Python3 有条件装饰?

发布于 2024-09-24 16:59:06 字数 301 浏览 0 评论 0原文

是否可以根据条件装饰函数?

a'la:

if she.weight() == duck.weight(): 
    @burn
def witch():
    pass

我只是想知道是否可以使用逻辑(当 witch 被调用时?)来确定是否用 @burn 装饰 witch

如果没有,是否可以在装饰器中创建一个条件以达到相同的效果? (女巫被称为未修饰的。)

Is it possible to decorate a function based on a condition?

a'la:

if she.weight() == duck.weight(): 
    @burn
def witch():
    pass

I'm just wondering if logic could be used (when witch is called?) to figure out whether or not to decorate witch with @burn?

If not, is it possible to create a condition within the decorator to the same effect? (witch being called undecorated.)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

一百个冬季 2024-10-01 16:59:06

您可以创建一个“有条件”装饰器:

>>> def conditionally(dec, cond):
    def resdec(f):
        if not cond:
            return f
        return dec(f)
    return resdec

用法示例如下:

>>> def burn(f):
    def blah(*args, **kwargs):
        print 'hah'
        return f(*args, **kwargs)
    return blah

>>> @conditionally(burn, True)
def witch(): pass
>>> witch()
hah

>>> @conditionally(burn, False)
def witch(): pass
>>> witch()

You can create a 'conditionally' decorator:

>>> def conditionally(dec, cond):
    def resdec(f):
        if not cond:
            return f
        return dec(f)
    return resdec

Usage example follows:

>>> def burn(f):
    def blah(*args, **kwargs):
        print 'hah'
        return f(*args, **kwargs)
    return blah

>>> @conditionally(burn, True)
def witch(): pass
>>> witch()
hah

>>> @conditionally(burn, False)
def witch(): pass
>>> witch()
温柔一刀 2024-10-01 16:59:06

可以通过重新分配启用/禁用装饰器

def 不变(func):
    “这个装饰器没有添加任何行为”
    返回函数

def 禁用(功能):
    “这个装饰器禁用了提供的功能,并且不执行任何操作”
    defempty_func(*args,**kargs):
        经过
    返回空函数

# 将其定义为等同于未更改,以实现禁用时的良好对称性
启用 = 不变

#
# 使用示例
#

GLOBAL_ENABLE_FLAG = 真

如果 GLOBAL_ENABLE_FLAG 则状态 = 启用,否则禁用
@状态
defspecial_function_foo():
    打印“功能已启用”

It is possible to enable/disable decorators by reassignment.

def unchanged(func):
    "This decorator doesn't add any behavior"
    return func

def disabled(func):
    "This decorator disables the provided function, and does nothing"
    def empty_func(*args,**kargs):
        pass
    return empty_func

# define this as equivalent to unchanged, for nice symmetry with disabled
enabled = unchanged

#
# Sample use
#

GLOBAL_ENABLE_FLAG = True

state = enabled if GLOBAL_ENABLE_FLAG else disabled
@state
def special_function_foo():
    print "function was enabled"
蒲公英的约定 2024-10-01 16:59:06

装饰器只是用于重新定义函数的语法糖,例如:

def wrapper(f):
    def inner(f, *args):
        return f(*args)
    return lambda *args: inner(f, *args)

def foo():
    return 4
foo = wrapper(foo)

这意味着您可以在语法糖存在之前以旧的方式进行操作:

def foo():
    return 4
if [some_condition]:
    foo = wrapper(foo)

Decorators are just syntactical sugar for re-defining the function, ex:

def wrapper(f):
    def inner(f, *args):
        return f(*args)
    return lambda *args: inner(f, *args)

def foo():
    return 4
foo = wrapper(foo)

Which means that you could do it the old way, before the syntactical sugar existed:

def foo():
    return 4
if [some_condition]:
    foo = wrapper(foo)
窗影残 2024-10-01 16:59:06

要创建条件装饰器,您可以创建一个接受参数的装饰器,如下所示

from functools import wraps

def burn(condition):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if condition:
                ## add witch burning logic here
                result = func(*args, **kwargs)
            else:
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@burn(condition)
def witch():
    pass

To create a conditional decorator you can create a decorator which accepts arguments as below

from functools import wraps

def burn(condition):
    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            if condition:
                ## add witch burning logic here
                result = func(*args, **kwargs)
            else:
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator

@burn(condition)
def witch():
    pass
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文