Python Forum
Why does this example need 'self'
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Why does this example need 'self'
#1
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
Yoriz write Feb-08-2022, 06:18 AM:
Please post all code, output and errors (in their entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.

Attached Files

.py   wanduhr_muloe.py (Size: 1.38 KB / Downloads: 168)
.py   time_and_date.py (Size: 3.17 KB / Downloads: 188)
Reply
#2
    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.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020