简体   繁体   English

将具有不同数量变量的参数传递给功能

[英]Pass parameters with different amount of variables to function

I am trying to create function that would take a random amount of parameters some defined, others not. 我正在尝试创建一个函数,该函数将接受一些定义的随机参数,而其他参数则没有。 So I have this search function that would sometimes take all of the arguments, but sometimes just url, query and authHeader. 因此,我具有此搜索功能,该功能有时会使用所有参数,但有时只会使用url,query和authHeader。

I did study about *arg, **kwards, but AFAIK they did not suit in this case. 我确实研究过* arg,** kwards,但是AFAIK在这种情况下不适合。 Or do I always have to give them some value in my case, for example "null"? 还是我必须始终为他们提供一些价值,例如“ null”? But that means I need to assign a value to variable and could not just pass it that time? 但是,这意味着我需要分配一个值变量,不能只是通过它那还得了?

def search(url, query, resultLimit, resultInfoSize, authHeader):
searchRequest = session.post(url + '/services/search?q=' + query + '&num=' + resultLimit + '&datalinesToReturn='+ resultInfoSize, headers=authHeader)
searchData = searchRequest.json()
return searchData

Any opinion much appreciated. 任何意见表示赞赏。

Update 更新

as @Jerrybibo kindly stated I got my aswer: 正如@Jerrybibo友善地表示,我知道了:

So adding if condition in the function was what I was looking for. 因此,添加条件是否是我想要的功能。 Changing the default values inside the function if on call none are provided. 如果未提供任何值,则在函数中更改默认值(未提供)。

def search(url, query, resultLimit, authHeader, resultLimit=None, resultInfoSize=None):
if resultLimit == None: resultLimit='50'
if resultInfoSize == None: resultInfoSize=''
searchRequest = session.post(url + '/services/search?q=' + query + '&num=' + resultLimit + '&datalinesToReturn='+ resultInfoSize, headers=authHeader)
searchData = searchRequest.json()
return searchData

Looking at your question, I believe one way of working around this is to have several of your function parameters set to default sentinel values (usually None ; use whichever default value makes sense in your scenario) so that you do not have to pass the values on function call; 看着你的问题,我认为解决这个工作的一个方式是有几个设置为默认定点值的函数的参数(通常是None ;无论使用哪一个默认值,使你的情况下意义上的),这样你就不必通过值在函数调用时; and if you do pass them, they get processed just like normal parameters. 如果您通过它们,它们将像普通参数一样被处理。 Your function definition would look like this: 您的函数定义如下所示:

def search(url, query, authHeader, resultLimit=None, resultInfoSize=None):

Additionally, you may have to change your searchRequest definition in the function in the event that resultLimit or resultInfoSize is None . 此外,如果resultLimitresultInfoSizeNone ,则可能必须在函数中更改searchRequest定义。

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

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