-2
我在python中調用一個類與許多可選參數。我這樣構造構造函數的原因是因爲我想有兩種可能性來創建員工對象的實例。Python構造函數與許多可選參數
def __init__(self, ssn=None, familyssn=None, first_name=None, last_name=None, middle_name=None, email=None, mobile_phone=None, phone=None, department=None, salary=None, employee_list=None):
self.employee_list = employee_list or []
dict_of_emp = {}
list_of_emp = []
self.ssn = ssn
self.familyssn = familyssn
self.first_name = first_name
self.last_name = last_name
self.middle_name = middle_name
self.email = email
self.mobile_phone = mobile_phone
self.phone = phone
self.department = department
self.salary = salary
list_of_emp.append(ssn)
list_of_emp.append(familyssn)
list_of_emp.append(first_name)
list_of_emp.append(last_name)
list_of_emp.append(middle_name)
list_of_emp.append(email)
list_of_emp.append(mobile_phone)
list_of_emp.append(phone)
list_of_emp.append(department)
list_of_emp.append(salary)
#print "listi i smid: ", list_of_emp
Employee.empCount += 1
print "loop through list in constructor: ", employee_list
這是調用構造函數的唯一方法嗎?
emp = Employee(None, None, None, None, None, None, None, None, None, None, list_of_list_emp_to_register)
我覺得它相當醜陋的語法!
不,你並不需要所有的'None's。你應該注意關於[keyword arguments]的文檔(https://docs.python.org/2/tutorial/controlflow.html#keyword-arguments)。另外,什麼是'list_of_list_emp_to_register'? – 2014-09-27 21:30:23
您也可以將您最後一次選擇的'employee = None'更改爲'employee = []',儘管可能會有一些驚愕與... – Makoto 2014-09-27 21:52:10