user2837806
user2837806

Reputation:

Can a class inherit the __init__() function? (Python)

When creating a class when do I need to use init()?

For the code below, when we create the PartTimeEmployee() class can we just inherit the init() from the Employee() class? Or should we retype it?

I found that both codes worked:

class Employee(object):

    def __init__(self, employee_name):
        self.employee_name = employee_name

    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 20.00

class PartTimeEmployee(Employee):

    def calculate_wage(self,hours):
        self.hours = hours
        return hours * 12.00

and

class Employee(object):

    def __init__(self, employee_name):
        self.employee_name = employee_name

    def calculate_wage(self, hours):
        self.hours = hours
        return hours * 20.00

class PartTimeEmployee(Employee):
    def __init__(self,employee_name):
        self.employee_name = employee_name

    def calculate_wage(self,hours):
        self.hours = hours
        return hours * 12.00

Is there some kind of best practice here?

Upvotes: 4

Views: 1369

Answers (1)

icktoofay
icktoofay

Reputation: 129099

No; __init__ is inherited like any other method. Because of this, however, you have to take special precautions when you do override it. For example, if we have a Person class:

class Person(object):
    def __init__(self, name):
        self.name = name

We want to make a new class named Employee that extends it to add a title attribute. We could repeat the logic in the Person constructor:

class Employee(Person):
    def __init__(self, name, title):
        self.name = name
        self.title = title

But if Person does something more involved, you probably don't want to do that. Instead, you need to use super to explicitly call the superclass's __init__:

class Employee(Person):
    def __init__(self, name, title):
        super(Employee, self).__init__(name)
        self.title = title

But in the simple case where the subclass has no additional initialization, feel free to omit __init__; it will indeed be inherited from the superclass appropriately.

Upvotes: 7

Related Questions