создать список экземпляров класса - PullRequest
0 голосов
/ 09 октября 2019
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 голосов
/ 09 октября 2019

Как уже говорили выше, в идеале вы должны хранить список сотрудников вне вашего 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)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...