I just started learning OOP and was trying to create a class but apperently i am not able to call the fuction within function
class WordPic:
def __init__(self,filename,outputname):
self.skipped = ["was","in","the","have","think","these","we","as"]
self.filename = filename
self.outputname = outputname
self.txt_freq = {}
def get_frequancy(self):
with open (self.file_location,"r") as f:
lines = f.read().lower()
splited_lines = lines.split()
for line in splited_lines:
if line not in self.skipped and line.isalpha():
line = line[0].upper() line[1:]
if line not in self.txt_freq:
self.txt_freq[line] = 1
else:
self.txt_freq[line] = 1
return self.txt_freq
def create_pic(self):
cloud = wordcloud.WordCloud(background_color="white")
cloud.generate_from_frequencies(self.txt_freq)
cloud.to_file("{}.jpg".format(self.outputname))
def create(self):
get_frequancy(self)
create_pic(self)
print("created")
wc = WordPic("try.txt","done")
wc.create()
the error that i encounter is
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [190], in <cell line: 2>()
1 wc= WordPic("try.txt","done")
----> 2 wc.create()
Input In [188], in WordPic.create(self)
28 def create(self):
---> 29 get_frequancy(self)
30 create_pic(self)
31 print("created")
NameError: name 'get_frequancy' is not defined
i am not able to find my way around if anyone can help. thank you
CodePudding user response:
get_frequancy
is not a nonlocal variable; it's a class attribute. It has to be accessed as such. (The same goes for create_pic
.)
def create(self):
self.get_frequancy()
self.create_pic()
print("created")
(While WordPic.get_frequancy(self)
would be sufficient in the example shown, calling instance methods like this runs into problems once you start taking inheritance into account.)