Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add method to initialized object (python)

I want to add a method to an object that has already been instantiated.

The object is an instance of type vaderSentiment.vaderSentiment.SentimentIntensityAnalyzer (Vader is a popular NLP model).

In order to get the predicted negative tone of a text I need to do the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

# Import model
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer

# Instantiate model
vader = SentimentIntensityAnalyzer()

# Get negative score
vader.polarity_scores('This text is awful').get('neg')
> 0.5

I would like to add a predict_proba method such that vader.predict_proba('This text is awful') would return 0.5.

Based on this question I tried:

# Define function
predict_proba(self, text):
    return self.polarity_scores(text).get('negative')

# Add method to instance
vader.predict_proba = predict_proba

# Attempt
vader.predict_proba('This text is awful')

Which throws:

TypeError: predict_proba() missing 1 required positional argument: ‘text’

>Solution :

If you want to activate __get__ protocol (if you don’t know what it is, you probably do want it:), add the method to the class, not the instance.

SentimentIntensityAnalyzer.predict_proba = predict_proba

You’ll also need del vader.predict_proba if you’re doing it all in one session, to remove the instance function you added, that would override this.

The Pythonic way to do this is to subclass.

class MySIA(SentimentIntensityAnalyzer):
    def predict_proba(self, text):
        return self.polarity_scores(text).get('negative')

vader = MySIA()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading