As I was reading this tutorial about tkinter for my first steps with GUI in Python, I realized that a class function was called inside the __init__ function.
I'd to like to understand, for what reason must be declared self.class_function() when calling a class function inside __init__ function?
I found this question with this answer below, which just says that it must be called self.class_function and not class_function, without providing any concept or explanation about why it must be done 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
2 Answers 2
My understanding is that the reason you must call method with self.method_name instead of method_name is because, under the hood, Python substitutes the self portion to the first argument of the method.
You can test this for yourself by defining a class called Foo:
class Foo:
def __init__(self):
self.fun()
def fun(self):
print("fun")
You can actually call the fun() method by performing the following:
foo = Foo()
Foo.fun(foo)
This will be the same as performing self.fun() from within the class.
Please note that you cannot access private fields statically (e.g Foo._private_method(foo).)
3 Comments
_private_method then sure you can. Python doesn't really have "private methods" anyway.for what reason must be declared self.class_function() when calling a class function inside
__init__function?
self.foo() refers to instance methods of the class and not static methods or another methods from other modules...
in that way you do something similar to this.foo() in other languages, in other words: self.foo() is meaning to call a foo method of that object!
1 Comment
staticmethods will be called, also, so will classmethods.
parse_fileis an instance method.MyClass.parse_file(self)