创建类的实例列表

2024-09-24 22:27:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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方法时可以从列表中删除该实例。你知道吗


Tags: ornonameselfinputifisdef
1条回答
网友
1楼 · 发布于 2024-09-24 22:27:47

正如上面提到的,您最好在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)

相关问题 更多 >