简体   繁体   English

我可以在 python 方法中要求参数子集吗?

[英]Can I require a subset of parameters in a python method?

I have a function that can take either 1 string or 4 strings:我有一个 function 可以带 1 个字符串或 4 个字符串:

def my_function(a, b, c, d, e):

I want the user to either pass in a , or to pass in b, c, d and e .我希望用户传入a或传入b, c, d and e I know that I can make them all default to None , but then I need to have logic in my code that ensures that we either get only a , or that we get values for all of b , c , d and e .我知道我可以将它们全部默认为None ,但是我需要在我的代码中包含逻辑,以确保我们要么只获得a ,要么获得所有bcde的值。

Is there a better way to structure this?有没有更好的方法来构建它? I really don't want to have two different methods, but that is also a possibility.我真的不想有两种不同的方法,但这也是一种可能。

Not 100% sure if this is what you're going for.不是 100% 确定这是否是您想要的。

But this could work:但这可以工作:

def my_function(*args):
    if len(args) == 1:
        a = args[0]
        # do stuff with a
    elif len(args) == 4:
        (b, c, d, e) = args
        # do stuff with b,c,d,e
    else:
        raise Exception("Expected 1 or 4 arguments: Got " + str(len(args)))

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

相关问题 如何验证使用包括数据帧在内的参数调用了 Python 方法? - How can I verify a Python method was called with parameters including a DataFrames? 我可以在python中使用`mock`来模拟具有指定参数的方法吗? - Can I mock a method with specified parameters by using `mock` in python? 如何在python中专注于列表的子集 - How can I focus on a subset of a list in python 我可以在 Python 中键入提示联合的子集吗? - Can I type hint a subset of a Union in Python? 在哪种情况下,我需要python类中的参数? - In what instance would I require parameters in python classes? 需要python函数中的命名参数 - require named parameters in python function 如何获取对象属性的子集作为 Python 字典? - How Can I Get a Subset of an Object's Properties as a Python Dictionary? 如何在不重新定义的情况下提取 python 枚举子集? - How can I extract a python enum subset without redefining it? 我怎样才能安全地执行 python 的一个子集? - How can I go about securely executing a subset of python? 如何在 Python 中使用 Kullback-Leibler 方法最小化 Weibull 分布的参数? - How can I minimize parameters of a Weibull Distribution using Kullback-Leibler method in Python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM