Skip to content Skip to sidebar Skip to footer

How Do I Change A SuperClass Attribute That's Inside Of A SubClass?

When I define the __init__ of ProductionWorker, I also need to set the attributes of EmployeeClass. I entered 'Bob' and '001121' as a test and it works but I need to be able to cha

Solution 1:

You have to use arguments as any with any other parameters:

class ProductionWorker(EmployeeClass):
    SHIFT = {1: "day shift", 2: "night shift"}

    def __init__(self, name, number, shift=None, hourly_pay=None):
        EmployeeClass.__init__(self,  name, number)
        self._shift = shift
        self.hourly_pay = hourly_pay

    @property
    def shift(self):
        return self._shift

    @shift.setter
    def shift(self, shift):
        if shift in ProductionWorker.SHIFT:
            self._shift = shift
        else:
            self._shift = None

    def __str__(self):
        summary = EmployeeClass.__str__(self)
        return summary + "They work on the {} and make ${:.2f} an hour.".format(
            ProductionWorker.SHIFT[self.shift], self.hourly_pay)

name = input("Enter the name of the employee: ")
number = input("Enter the ID number of the employee: ")
shift = int(input("Enter 1 if they work day shift or 2 if they work night shift: "))
hourly_pay = float(input("Enter how much they make hourly (numerical): "))

z = ProductionWorker(name, number, shift, hourly_pay)
print(z)

Solution 2:

I would include the parameters of the EmployeeClass in the init method parameters of the ProductionWorker to pass along to the superclass.

For python 3 you can do super().__init___() rather than EmployeeClass.__init__().

Additionally you should consider using descriptors rather than implementing getters and setters as that is the pythonic way to do that.

class ProductionWorker(EmployeeClass):
    def __init__(self, name, number, shift=None, hourly_pay=None):
        super().__init__(name, number)
        self.__shift = shift
        self.__hourly_pay = hourly_pay

Post a Comment for "How Do I Change A SuperClass Attribute That's Inside Of A SubClass?"