Pyth0nicPenguin
Pyth0nicPenguin

Reputation: 148

How to use the __init__ from the main object class in an inherited class?

I have a program that I will be using inheritance in:

class Templates(object):

    def __init__(self, esd_user, start_date,
                 summary, ticket_number, email_type):
        self.esd = esd_user
        self.strt_day = start_date
        self.sum = summary
        self.ticket = ticket_number
        self.email = email_type

    def gather_intel(self):
        if self.email == "pend":
            PendingEmail(self.esd, self.ticket,
                         self.strt_day)
        elif self.email == "generic":
            GenericEmail(self.esd, self.ticket,
                         self.strt_day)
        elif self.email == "resolve":
            ResolveEmail(self.esd, self.ticket,
                         self.strt_day)
        elif self.email == "osha":
            OshaEmail(self.esd, self.ticket,
                      self.strt_day)
        else:
            return False


class PendingEmail(Templates):
    pass


class GenericEmail(Templates):
    pass


class ResolveEmail(Templates):
    pass


class OshaEmail(Templates):
    pass

Is it possible for me to use the __init__ from the Templates class as the __init__ for the other inherited classes, without having to rewrite the __init__ method? Would a call to super be necessary here?

For example, is this the proper way to inherit the __init__ function from the main Templates class?

class PendingEmail(Templates):

    def __init__(self):
        super(Templates, self).__init__()

Upvotes: 0

Views: 62

Answers (3)

sureshvv
sureshvv

Reputation: 4422

If you don't define an __init__ method in your subclass, your base class __init__ will still get called. If you define one, then you need to explicitly call it like you have described before/after any other actions you need. The first argument to super is the class where it is being called.

Upvotes: 0

user2357112
user2357112

Reputation: 281748

Like any other method, classes automatically inherit __init__ from their superclasses. What you want to achieve is already happening.

Upvotes: 0

ShadowRanger
ShadowRanger

Reputation: 155574

If you don't need to add anything to the __init__ for the subclasses, just don't implement it, and they'll inherit it automatically. Otherwise, you're a little off for cases where you need to do further initialization:

class PendingEmail(Templates):

    def __init__(self):
        super(PendingEmail, self).__init__()  # Name your own class, not the super class

Upvotes: 1

Related Questions