[英]Python - How to make a class method that receives any number of args and returns a list of all args?
我創建了一個名為 Manager 的類作為 Employee 的子類,並且正在嘗試創建一個常規方法來將員工添加到經理的監督中。 但是,我希望此方法接收任意數量的參數(員工數量),因此我在定義該方法時添加了 *:
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
# Returns employees fullname
def fullname(self):
return '{} {}'.format(self.first, self.last)
class Manager(Employee):
def __init__(self, first, last, pay, employees=None):
super().__init__(first, last, pay)
if employees is None:
self.employees = []
else:
self.employees = employees
def add_emp(self, *emp): # Accept any no. of args
if emp not in self.employees:
self.employees.append(emp)
def print_emps(self): # Prints all employees' names
for emp in self.employees:
print('-->', emp.fullname())
當我運行像 (emp_1, emp_2, emp_3) 這樣的代碼 addind emps 時,它們會被添加,但是在打印它們的名稱時會發生錯誤:
emp_1 = Employee('Corey', 'Schafer', 50000)
emp_2 = Employee('Test', 'User', 60000)
mng_1 = Manager('Roger', 'Smith', 100000)
mng_1.add_emp(emp_1, emp_2)
mng_1.print_emps()
AttributeError: 'tuple' object has no attribute 'fullname'
如何輸入盡可能多的參數作為列表,以便類的屬性和方法對每個項目保持有效?
像這樣改變你的 add_emp 方法:
def add_emp(self, *emps): # Accept any no. of args
for emp in emps:
if emp not in self.employees:
self.employees.append(emp)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.