Search code examples
pythonoopinitsuper

How to properly use super().__init__() in python 3?


I've written the following code, which raises an error. I'd like to know what I should revise my code to in order to successfully execute as well as the rules governing its operation so that I can avoid this issue in the future.

What I'm trying to do here is define a class, DataLoader, which loads a corpus, breaks into training and testing sets, as well as full and test vocab sets. All this works out no issues.

The problems arise when I try to inherit the DataLoader class in the Model class. I want to initialize an instance of the Model class with all the attributes of the DataLoader class, plus an additional attribute, n. I'm unclear on why this code doesn't accomplish this effect.


from nltk.corpus import brown

class DataLoader():

    def __init__(self,data,train_ratio):
        self.all = [sent for sent in data.sents()]

        num_ex = len(self.all)
        num_train = int(train_ratio * num_ex)

        self.train = [word.lower() for sent in self.all[:num_train] for word in sent] 
        self.test = [word.lower() for sent in self.all[num_train:] for word in sent] 

        self.full_vocab = [word.lower() for word in set(data.words())]
        self.train_vocab = list(set(self.train))

        return None

class Model(DataLoader):

    def __init__(self,data,train_ratio,n):

        self.n = n
        super().__init__(self,data,train_ratio)

bgrams = Model(data=brown, train_ratio=0.5, n=2)

And the following error is raised:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-16-d641225c06d6> in <module>()
----> 1 bgrams = Model(data=brown,train_ratio=0.5,n=2)
      2 # bgrams.compute_bigram()

<ipython-input-15-98b0485bce38> in __init__(self, data, train_ratio, n)
      9 
     10         self.n = n
---> 11         super(Model).__init__(self,data,train_ratio)
     12 
     13 

TypeError: super() takes at most 2 arguments (3 given)


Solution

  • Simple, just remove self from the super clause; your code should look like this:

    
    class Model(DataLoader):
    
        def __init__(self,data,train_ratio,n):
    
            self.n = n
            super().__init__(data,train_ratio)