Python-如何制作一个可以接收任意数量的args并返回所有args列表的类方法?

时间:2018-11-03 14:48:01

标签: python python-3.x class inheritance

我创建了一个称为Manager的类,作为Employee的子类,并且正在尝试创建一种常规方法来将addind员工纳入经理的监督。但是我希望此方法可以接收任意数量的参数(雇员人数),因此在定义该方法时添加了*:

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'

如何在列表中输入尽可能多的args,以使该类的属性和方法仍可用于每个项目?

1 个答案:

答案 0 :(得分:0)

像这样更改您的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)