简体   繁体   English

有没有办法知道函数中传递了多少个参数?

[英]Is there a way to know how many arguments are passed in a function?

Referring to the question above, is there a way to identify how many arguments are passed to a function. 参考上面的问题,有没有办法确定传递给函数的参数数量。

def setup(file1, file2):
    reader1 = PyPDF2.PdfFileReader(file1)
    reader2 = PyPDF2.PdfFileReader(file2)

My goal is to make the function versatile. 我的目标是使功能多才多艺。 My plan is to detect how many arguments are passed and then modify the behavior of the function such as, if three files are passed to the function, it will create 3 readers. 我的计划是检测传递了多少个参数然后修改函数的行为,例如,如果将三个文件传递给函数,它将创建3个读者。 I'll use for loop to name the readers and pass the right files to the PdfFileReader() function. 我将使用for循环来命名读者并将正确的文件传递给PdfFileReader()函数。 But, I just do not know how to make the function behave like how I want it to be in the first place. 但是,我只是不知道如何让函数表现得像我想要的那样。

You can use variable arguments instead: 您可以使用变量参数:

def setup(*files):
    readers = [PyPDF2.PdfFileReader(file) for file in files]
    return readers

so if, for example, you want call it with 3 files, you can call it with: 因此,例如,如果你想用3个文件调用它,你可以用以下方法调用它:

reader1, reader2, reader3 = setup(file1, file2, file3)

You can make use of *args . 你可以使用*args Just do like: 就像这样:

def setup(*args):
    reader_list = [PyPDF2.PdfFileReader(el) fro el in args]

Use the variable number of arguments syntax. 使用可变数量的参数语法。 For example: 例如:

def foo(*args):
   print(len(args))

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

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