Add method to initialized object (python)

Question:

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:

# 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’

Asked By: Arturo Sbr

||

Answers:

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()
Answered By: Veky