You cannot call them explicitly. For instance, when you create a new object, Python automatically calls the __new__ method, which in turn calls the __init__ method. The __str__ method is called when you print() an object.
Calling other methods from the __init__ methodWe can call other methods of the class from the __init__ method by using the self keyword. The above code will print the following output.
To call a function within class with Python, we call the function with self before it. We call the distToPoint instance method within the Coordinates class by calling self. distToPoint . self is variable storing the current Coordinates class instance.
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
.
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()
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]
.
You must declare parse_file like this; def parse_file(self)
. The "self" parameter is a hidden parameter in most languages, but not in python. You must add it to the definition of all that methods that belong to a class.
Then you can call the function from any method inside the class using self.parse_file
your final program is going to look 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With