简体   繁体   English

如何使用装饰器修改* args的类型?

[英]How can I use a decorator to modify the type of *args?

I would like to use a @decorator to allow me to be able to access ' - '.join(args) as args , as depicted below. 我想用一个@decorator ,让我能够访问' - '.join(args)args ,如下式所示。 Is this possible, using a metaclass perhaps? 这可能是使用元类吗?

def a(*args):
    print(args)
a(1, 2, 3)
# (1, 2, 3)

@magic
def b(*args):
    print(args)
b(1, 2, 3)
# 1 - 2 - 3

You can get close: 你可以近距离接触:

def magic(func):
    def wrapper(*args):
        return func(' - '.join(map(str, args)))
    return wrapper

but this prints out ('1 - 2 - 3',) because the body of b sees args as a tuple due to the *args , and I doubt a decorator can get around that. 但这打印出来('1 - 2 - 3',)因为b的主体因为*args而将args视为元组,我怀疑装饰者可以解决这个问题。 What do you expect to happen if the body is something like print(args[1]) ? 如果身体像print(args[1])你会发生什么?

So part of the problem is that you're using integers where you need strings, so convert them into strings and then use the join function. 所以问题的一部分是你在需要字符串的地方使用整数,所以将它们转换成字符串然后使用join函数。

def magic(func):
    def wrapper(*args):
        return ' - '.join(map(str, args))
    return wrapper

@magic
def a(*args):
    return 'Arguments were {}.'.format(args)

print(a(1, 2, 3))

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM