Python: Class: __init__, super()

nick3499
1 min readMay 3, 2017

--

In the Python module example below, the built-in super() function returns a proxy object which commits method calls to the parent class, specifically the Contact() class.

Without super(), the Friend() subclass would need to duplicate code in order to set up the name and email properties—the same way they were set up in the Contact() parent class. Also, without super(), the Friend() subclass would fail to add contacts to all_contacts list. And the code would need to be updated in two or more places.

$ python -i class_init_super.py
>>> issubclass(Friend, Contact)
True
>>> c = Contact("John Smytherson", "jsmytherson@example.com")
>>> f = Friend("Jane Doe", "jdoe@example.com", "000-000-0000")
>>> c.all_contacts
[<__main__.Contact object at 0x7ff0f538bd68>, <__main__.Friend object at 0x7ff0f538bda0>]
>>> c.name
'John Smytherson'
>>> f.name
'Jane Doe'
>>> c.email
'jsmytherson@example.com'
>>> f.email
'jdoe@example.com'
>>> f.phone
'000-000-0000'

https://docs.python.org/3/library/functions.html#super

--

--

nick3499
nick3499

Written by nick3499

coder of JavaScript and Python

No responses yet