在Python中遍历函数参数

0 投票
4 回答
1699 浏览
提问于 2025-04-18 01:00

我该如何遍历我的参数,以便为我函数中的每个参数打印这些行,而不是一个个手动输入呢?

def validate_user(surname, username, passwd, password, errors):

    errors = []

    surname = surname.strip() # no digits
    if not surname:
        errors.append('Surname may not be empty, please enter surname') 
    elif len(surname) > 20:
        errors.append('Please shorten surname to atmost 20 characters')

    username = username.strip()
    if not username:
        errors.append('Username may not be empty, please enter a username') 
    elif len(surname) > 20:
        errors.append('Please shorten username to atmost 20 characters')

4 个回答

0

你可以通过把每个参数放在一个列表里,在函数内部逐个处理它们:

def validate(a,b,c):
    for item in [a,b,c]:
        print item

a=1
b=2
c=3

validate(a,b,c)
1

除了所有的回答,你还可以使用inspect库

>>> def f(a,b,c):
...   print inspect.getargspec(f).args
...
>>> f(1,2,3)
['a', 'b', 'c']
>>> def f(a,e,d,h):
...   print inspect.getargspec(f).args
...
>>> f(1,2,3,4)
['a', 'e', 'd', 'h']

补充说明:不使用函数的名字:

>>> def f(a,e,d,h):
...   print inspect.getargvalues(inspect.currentframe()).args
...
>>> f(1,2,3,4)
['a', 'e', 'd', 'h']

这个函数可能看起来像这样:

def validate_user(surname, username, passwd, password, errors):
    errors = []
    for arg in inspect.getargspec(validate_user).args[:-1]:
        value = eval(arg)
        if not value:
            errors.append("{0} may not be empty, please enter a {1}.".format(arg.capitalize(), arg))
        elif len(value) > 20:
            errors.append("Please shorten {0} to atmost 20 characters (|{1}|>20)".format(arg,value))
    return errors


>>> validate_user("foo","","mysuperlongpasswordwhichissecure","",[])
['Username may not be empty, please enter a username.', 'Please shorten passwd to atmost 20 characters (|mysuperlongpasswordwhichissecure|>20)', 'Password may not be empty, please enter a password.']
2

你真正想要的是局部变量。

def f(a, b, c):
    for k, v in locals().items():
        print k, v

或者类似的东西。

2

形成一个包含这些参数的列表:

def validate_user(surname, username, passwd, password, errors):
    for n in [surname, username]:
        n = n.strip()
        # Append the following printed strings to a list if you want to return them..
        if not n:
            print("{} is not valid, enter a valid name..".format(n))
        if len(n) > 20:
            print("{} is too long, please shorten.".format(n))

我需要说明,这个方法其实只适用于简单的姓氏或用户名验证。

撰写回答