Python Forum

Full Version: Why does this example need 'self'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi there

This is a teaching example and I don't understand why I need the 'self' keyword here. Can somebody explain this?

time_and_date.py
- has the classes Clock & Calendar

wanduhr_muloe.py
- "Combines" Clock and Calendar from above for a wall clock

My question: wanduhr_muloe.py Line 27:
return f'{Calendar.__str__(self)} - {Clock.__str__(self)}'
Why do I need these 2 selfs? In my mind it should more be something like super(), as they come from the class Clock & Calendar respectively. Wall
    def __str__(self):
        '''Returns the time and date as formatted string.
        '''
        return f'{Calendar.__str__(self)} - {Clock.__str__(self)}'
self in "def __str__(self)"" is used to accept the instance argument that Python automatically prepends to the argument when calling an instance method. The method __str__() passes this instance as an argument when it calls the __str__() method of its parent classes; Calendar and Clock. Finally, __str__() is the method Python automatically selects to convert an object to a str for the purposes of printing (or if you call str(object)).

Python actually does this behind your back all the time. Python converts this code:
cal_clock = CalendarWallClock()
print(cal_clock)
into
cal_clock = CalendarWallClock()
print(CalendarWallClock.__str__(cal_clock)
It is done differently in the CalendarWallClock.__str__() method because the code wants to call the __str__() methods defined by Calendar and Clock, not the __str__() method defined by CalendarWallClock.