将继承的类更改为保留属性的另一个继承的类

时间:2019-12-07 11:31:52

标签: python python-3.x oop

我需要将一个继承的类更改为另一个仅更改了一个属性的继承的类

我需要将出纳员“提升”为经理,唯一可以改变的就是工资

收银员和经理都是员工的继承类(我不确定我是否在正确使用“ hasattr”功能)

class Employee:
  def __init__(self,name):
    self.name=name
    if(hasattr(self,'shifts')==False):
        self.shifts=[]
class Manager(Employee):
  def __init__(self,name,salary):
    Employee.__init__(self,name)
    self.salary=salary
class Cashier(Employee):
  def __init__(self,name,salarey_per_hours):
    Employee.__init__(self,name)
    self.salery_per_hours=salarey_per_hours
  def promote(self,salary):
    return Manager(self.name,salary)

P.s这是我第一次上传问题

2 个答案:

答案 0 :(得分:1)

您可以做的是创建类的加法,然后将self添加到要返回的管理器类中,如下所示:

class Employee(object):
    def __init__(self, name):
        self.name=name
        if not hasattr(self, 'shifts'):
            self.shifts = []

    def __add__(self, other):
        if isinstance(other, Employee):
            for key, value in other.__dict__.items():
                if key == 'salary':
                    continue
                self.__setattr__(key, value)
        return self


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


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

    def promote(self, salary):
        manager = Manager(self.name, salary)
        manager += self
        return manager


cashier = Cashier('hank', 22)
cashier.shifts = [1, 2, 3, 4]
print(cashier.shifts)
promoted_cashier = cashier.promote(30)
print(promoted_cashier.shifts)

在这里,请确保将除“工资”以外的所有内容都转移到升级的类中。而且由于经理和收银员都是雇员,因此应该很好地工作。我将您的代码更改为我以前使用的代码,因为在您初始化时有一些不寻常的编码与Calling Employee一起使用,我认为您没有明确需要。抱歉,如果不是这样。

答案 1 :(得分:0)

您可以通过obj.__class__将对象的类更改为另一个类 做obj.__class__ = SomeClass

提防,如果处理不当,可能会导致奇怪的行为。

通过修改代码

class Employee:
  def __init__(self,name):
    self.name=name
    if(hasattr(self,'shifts')==False):
        self.shifts=[]

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

class Cashier(Employee):
  def __init__(self,name,salarey_per_hours):
    Employee.__init__(self,name)
    self.salery_per_hours=salarey_per_hours
  def promote(self,salary):
    self.__class__ = Manager
    # return Manager(self.name,salary)

您也可以查看此帖子changing the class of a python object (casting)