简体   繁体   English

使Python 3函数接受预设的正确方法是什么?

[英]What's the proper way to make a Python 3 function accept presets?

Consider a function that takes three arguments: 考虑一个带有三个参数的函数:

def foo(arg1, arg2, arg3):
    pass

and a class that provides presets in a tuple: 以及在元组中提供预设的类:

class Presets():
    preset1 = (1, 2, 3)
    preset2 = (3, 2, 1)

What's the proper way to make the function accept either three seperate arguments or one tuple of arguments? 使函数接受三个单独的参数或一个参数元组的正确方法是什么?

Both should be valid function calls: 两者都应该是有效的函数调用:

foo(1,1,1)
foo(Presets.preset2)

One way to do it is by using a decorator. 一种方法是使用装饰器。

from functools import wraps

def tupled_arguments(f):
    @wraps(f)  # keeps name, docstring etc. of f
    def accepts_tuple(tup, *args):
        if not args:  # only one argument given
            return f(*tup)
        return f(tup, *args)
    return accepts_tuple

@tupled_arguments
def foo(arg1, arg2, arg3):
    pass

Now the function can be called by either passing all arguments seperately or by passing them in a sequence. 现在可以通过单独传递所有参数或者按顺序传递它们来调用该函数。

foo(1,2,3)
foo((1,2,3))
foo([1,2,3])

are all equal calls. 都是平等的电话。

The simplest way is to just use an asterisk * to cause the arguments to be flattened when passed to foo : 最简单的方法是只使用星号*使参数在传递给foo时被展平:

foo(*Presets.preset2)

This is equivalent to: 这相当于:

foo(*(3, 2, 1))

which is equivalent to: 这相当于:

foo(3, 2, 1)

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

相关问题 在Python中打破嵌套函数/构造函数调用的正确方法是什么? - What's the proper way to break nested function/constructor calls in Python? 在python中编写syslog函数的正确方法是什么? - What is the proper way to write a syslog function in python? 在python中使类数据可以继承的正确方法是什么? - What is the proper way to make class data inheritable in python? 在Python中编写游戏循环的正确方法是什么? - What's the proper way to write a game loop in Python? 使用Python模块Scholar.py的正确方法是什么? - What's the proper way to use the Python module scholar.py? 为 Python 安装 pip、virtualenv 和分发的正确方法是什么? - What's the proper way to install pip, virtualenv, and distribute for Python? 在 Python 中访问 Gravity 的正确方法是什么? - What's the proper way to access Gravity Forms API in Python? 异步运行某些 Python 代码的正确方法是什么? - What's the proper way to run some Python code asynchronously? Python-在另一个类中对方法进行单元测试的正确方法是什么? - Python - What's the proper way to unittest methods in a different class? 在python 2.7中打开文件的正确方法是什么? - What's the proper way to open a file in python 2.7?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM