-1

I am learning Object-oriented programming and I am having trouble with the parameter of "self".

Here is my code for analysing text.

class analysedText(object):
    
    def __init__ (self, text):
        formatted_text=text.replace(".","").replace("!","").replace(",","").replace("?","")
        lower_text=formatted_text.lower()
        self.fmtText=lower_text
    
    def freqAll(self):
        word_list=self.fmtText.split(' ')
        dic={}
        for i in set(word_list):
            dic[i]=word_list.count(i)
        
        return dic
            
    def freqOf(self,word):
        freqDict=self.freqAll()
        
        if word in freqDict:
            return freqDict[word]
        else:
            return 0

I just learned that self refers to instance of the class. However, I can't understand the meaning of self.fmtText and self.freqAll(). Can anyone give me a specific explanation, please? Thanks in advance!

azro
  • 53,056
  • 7
  • 34
  • 70
MR Li
  • 39
  • 5
  • 1
    Does this answer your question? [What is the purpose of the word 'self'?](https://stackoverflow.com/questions/2709821/what-is-the-purpose-of-the-word-self) – Joshua Nixon Jun 26 '21 at 08:58
  • `self.fmtText` get the `fmtText` from object `self`. `self.freqAll()` calls method `freqAll()` on object `self`. You may read more tutorial on OOP because that's the very basics – azro Jun 26 '21 at 08:59

1 Answers1

1

self represents the instance of the class. By using the “self” keyword we can access the attributes and methods of the class in python. It binds the attributes with the given arguments.

self.fmtText is used to access the class variable and self.freqAll() calls the instance method freqAll().

Shradha
  • 2,232
  • 1
  • 14
  • 26