Probably a dumb question right here.
I'm new to programming, but from my understanding we need to use nameofthemetod() to recall a method.
I don't understand why sometimes, using a class, this rule is not longer valid and instead we recall it using self.nameofthemethod(). Wasn't the self. supposed to work only for variables?
Here is an example:
class Statusbar:
def __init__(self, parent):
self.status = tk.StringVar()
self.status.set("PyText - 0.1 Gutenberg")
def update_status(self):
self.status.set("Your file has been saved")
def save(self):
self.update_status() # why the self? Shouldn't it be just update_status()?
Didn't paste the whole code, but I hope you get the idea
CodePudding user response:
Since the methods (like class variables) are defined in a class and as part of the class, they must be referenced as such. When calling update_status()
outside of StatusBar
, it must be called as StatusBar.update_status()
, because it is part of the StatusBar
class:
class Statusbar:
def __init__(self, parent):
self.status = tk.StringVar()
self.status.set("PyText - 0.1 Gutenberg")
def update_status(self):
self.status.set("Your file has been saved")
def save(self):
self.update_status()
sb = StatusBar(some_window) # Here we create an instance of StatusBar
sb.update_status() # Here, we call StatusBar's method: update_status()
The same goes when calling update_status()
from inside the class. self
, as the name suggests, is simply a class's way of referencing itself. When the class calls self.update_status()
, it's basically saying "Call my update_status() method." Try printing self
; the output will be something like this:
<__main__.Statusbar object at 0x7efdd6445040>
The point is, since update_status()
is a method, and therefore part of the class (like the variable self.status
), it must be treated as such, whether you're calling it from inside or outside the class.