迭代函数参数python

时间:2014-04-02 13:20:51

标签: python function arguments iteration

如何迭代我的参数来为我的函数中的每个参数打印这些行,而不是输入每个参数?

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 :(得分: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))

我应该注意,这只适用于简单的姓氏或用户名验证。

答案 1 :(得分:1)

你真正想要的是当地人。

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

或类似的东西。

答案 2 :(得分:0)

您可以通过将每个参数放在函数中的列表中来迭代它们:

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

a=1
b=2
c=3

validate(a,b,c)

答案 3 :(得分:0)

除了所有答案外,您还可以使用inspect library

>>> 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.']