Alex
Alex

Reputation: 151

Python super class __init__()?

class Fetcher:
    def __init__(self):
        self.opener = urllib.opener()
    def query(self, something):
        self.opener.open(something)

class Person (Fetcher):
    def __init__(self):
         super().__init__()
         super().function()
    def fetch(self):
        super().query()

How can I rewrite Fetcher query method to skip Fetcher.init for every Person to obtain self.opener? Or even my pattern is wrong? If that is Ok, what about memory?

Upvotes: 0

Views: 282

Answers (1)

Moses Koledoye
Moses Koledoye

Reputation: 78546

You would naturally call the __init__ of the superclass while initialising the subclass. However, you can avoid defining a new opener object per instance by making it a class attribute of the superclass:

class Fetcher:
    opener = urllib.opener()
    def __init__(self):
        pass

    def query(self, something):
        self.opener.open(something)

class Person (Fetcher):
    def __init__(self):
        super().__init__()
        super().function()

    def fetch(self):
        super().query()

Upvotes: 1

Related Questions