I'm learning multiple inheritance in Python3. I'm wondering why the case# 1 works but case# 2 doesn't. Here are my code snippets.
class ContactList(list):
def search(self, name):
"""Return all contacts that contain the search value
in their name."""
matching_contacts = []
for contact in self:
if name in contact.name:
matching_contacts.append(contact)
return matching_contacts
class Contact:
all_contacts = ContactList()
def __init__(self, name="", email="", **kwargs):
super().__init__(**kwargs)
self.name = name
self.email = email
Contact.all_contacts.append(self)
print("Cotact")
class AddressHolder:
def __init__(self, street="", city="", state="", code="", **kwargs):
super().__init__(**kwargs)
self.street = street
self.city = city
self.state = state
self.code = code
print("AddressHolder")
class Friend(Contact, AddressHolder):
# case# 1
# def __init__(self, phone="", **kwargs):
# self.phone = phone
# super().__init__(**kwargs)
# print("Friend")
# case# 2
def __init__(self, **kwargs):
self.phone = kwargs["phone"]
super().__init__(**kwargs)
print("Friend")
if __name__ == "__main__":
friend = Friend(
phone="01234567",
name="My Friend",
email="[email protected]",
street="Street",
city="City",
state="State",
code="0123")
Here is the out put of the script. If I use only kwargs (case# 2) as a parameter in "Friend" that inherits "Contact" and "AddressHolder" then Python throughs error. I already tested the same type of construct without inheritance, except object, that worked perfectly.
"""
case 1#
$ python contacts.py
AddressHolder
Cotact
Friend
>>> friend.name
'My Friend'
>>> friend.phone
'01234567'
>>>
"""
"""
case 2#
$ python contacts.py
Traceback (most recent call last):
File "contacts.py", line 55, in <module>
code="0123")
File "contacts.py", line 43, in __init__
super().__init__(**kwargs)
File "contacts.py", line 16, in __init__
super().__init__(**kwargs)
File "contacts.py", line 25, in __init__
super().__init__(**kwargs)
TypeError: object.__init__() takes no parameters
>>>
"""