David542
David542

Reputation: 110382

Inherit and then override parent init

I have the following code:

# file1.py
class GenericScript(object):

    def __init__(self):

        self.start_time = time.time()
        self.date_stem = str(timezone.now().date()).replace('-','')
        self.script_name = os.path.basename(sys.argv[0]).replace('.py','')
        self.file_name = None
        self.log_file = None
        self.integrity_field = '%s+%s' % (self.script_name, str(int(time.time())))


# file2.py
class RTUpdater(GenericScript):

    def __init__(self):

        self.integrity_field = '%s+%s' % (self.script_name, self.date_stem)
        self.update_title_data = False
        self.update_title_ranking = True
        self.update_title_box_office = True
        self.update_person_ranking = True

What I am trying to do is call RTUpdate() and get it to initialize all the items first in the parent Class and then add to those with its own __init__ method. However, when I call it, the self.integrity_field keep raising an error because self.script_name is not defined, meaning it's not first inheriting the parent __init__ variables. Here is how I'm calling it:

if __name__ == '__main__':
    x = RTUpdater()
    main(x)

>>> AttributeError: 'RTUpdater' object has no attribute 'script_name'

What am I doing wrong and how would I fix this?

Upvotes: 0

Views: 399

Answers (2)

Chris
Chris

Reputation: 137071

You need to explicitly call the constructor of the parent class. Based on your inheritance of object I'm guessing you're using Python 2, so try this:

class RTUpdater(GenericScript):
    def __init__(self):
        super(RTUpdater, self).__init__()
        # ...

If you are actually using Python 3 you can just use super().__init__().

Upvotes: 1

MSeifert
MSeifert

Reputation: 152725

You completly override __init__ as far as I see it. Just call super().__init__() in your inherited __init__ (so that the init of the parent will be run) and check if the error still persists.

Or if you are using Python 2 you need to fix the classes for the super call: super(RTUpdater, self).__init__().

Upvotes: 1

Related Questions