[英]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.