Calling a class function inside of __init__
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Question
01:44 Accepted answer (Score 294)
02:15 Answer 2 (Score 59)
02:55 Answer 3 (Score 17)
03:40 Answer 4 (Score 1)
04:27 Thank you
--
Full question
https://stackoverflow.com/questions/1264...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #class
#avk47
ACCEPTED ANSWER
Score 304
Call the function in this way:
self.parse_file()
You also need to define your parse_file() function like this:
def parse_file(self):
The parse_file method has to be bound to an object upon calling it (because it's not a static method). This is done by calling the function on an instance of the object, in your case the instance is self.
ANSWER 2
Score 60
If I'm not wrong, both functions are part of your class, you should use it like this:
class MyClass():
def __init__(self, filename):
self.filename = filename
self.stat1 = None
self.stat2 = None
self.stat3 = None
self.stat4 = None
self.stat5 = None
self.parse_file()
def parse_file(self):
#do some parsing
self.stat1 = result_from_parse1
self.stat2 = result_from_parse2
self.stat3 = result_from_parse3
self.stat4 = result_from_parse4
self.stat5 = result_from_parse5
replace your line:
parse_file()
with:
self.parse_file()
ANSWER 3
Score 18
How about:
class MyClass(object):
def __init__(self, filename):
self.filename = filename
self.stats = parse_file(filename)
def parse_file(filename):
#do some parsing
return results_from_parse
By the way, if you have variables named stat1, stat2, etc., the situation is begging for a tuple:
stats = (...).
So let parse_file return a tuple, and store the tuple in
self.stats.
Then, for example, you can access what used to be called stat3 with self.stats[2].
ANSWER 4
Score 0
In parse_file, take the self argument (just like in __init__). If there's any other context you need then just pass it as additional arguments as usual.