创建一个类的实例列表

时间:2019-10-08 22:46:18

标签: python class oop

class Employee():
    def __init__(self, name, salary=0):
        self.name = name
        self.salary = salary

    def hire(self):
        hired = input('is employee hired? enter yes or no')
        if 'yes' in hired:
            hiresalary = int(input('enter employee salary'))
            self.salary = hiresalary

    def fire(self):
        fired = input('is employee fired? enter yes or no')
        if 'yes' in fired:
            employeelist.remove(self.name)
        if 'no':
            pass
    def raise_salary(self):
        input("do you want to raise {}'s salary, enter yes or no".format(self.name))
        if 'yes':
           raise_sum =  int(input("by how much do you want to raise {} salary?".format(self.name)))
           self.salary += raise_sum
        if 'no':
            pass

我想知道是否有一种方法可以将类的每个实例存储在列表中,以便如果我调用fire方法,可以从列表中删除该实例。

1 个答案:

答案 0 :(得分:0)

如上述人士所述,理想情况下,您应该存储Employee类之外的员工列表。然后,您可以更改Employee.fire()方法以接受员工列表,如下所示:

employees = []

class Employee():
    def __init__(self, name, salary=0):
        self.name = name
        self.salary = salary

    def hire(self):
        hired = input('is employee hired? enter yes or no')
        if 'yes' in hired:
            hiresalary = int(input('enter employee salary'))
            self.salary = hiresalary

    def fire(self, employeelist):
        fired = input('is employee fired? enter yes or no')
        if 'yes' in fired:
            employeelist.remove(self)
        return employeelist

    def raise_salary(self):
        input("do you want to raise {}'s salary, enter yes or no".format(self.name))
        if 'yes':
           raise_sum =  int(input("by how much do you want to raise {} salary?".format(self.name)))
           self.salary += raise_sum
        if 'no':
            pass

bob = Employee('Bob', 50)
employees.append(bob)

sally = Employee('Sally', 75)
employees.append(sally)
employees = bob.fire(employees)