简体   繁体   中英

Python - How to make a class method that receives any number of args and returns a list of all args?

I created a Class called Manager as a sub-class of Employee and am trying to create a regular method for addind employees to the manager's supervision. However I want this method to receive any number of arguments (number of employees) so I added the * when defining the method:

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

When I run the code addind emps like (emp_1, emp_2, emp_3) they're added, but when it comes to print their name an error occurs:

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'

How could input as many args as I want as a list so the attributes and methods of the class remain working for each item?

Change your add_emp method like this:

def add_emp(self, *emps):           # Accept any no. of args
    for emp in emps:
        if emp not in self.employees:
            self.employees.append(emp)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM