2014-04-02 40 views
0

如何迭代我的參數來爲我的函數中的每個參數打印這些行,而不是輸入每個參數?通過函數參數進行迭代python

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') 

回答

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)) 

我要指出,這是真的僅適用於簡單的姓氏或用戶名驗證。

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

你真正想要的是當地人。

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

或類似的東西。

+0

你可以用'''args'''和''''kwargs'''獲得相似的行爲,螞蟻可能會點亮清潔/清潔 – wnnmaw

+0

種,除非你調用的功能,然後你不知道它的參數是什麼。 – acushner

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