【发布时间】:2017-09-05 10:37:14
【问题描述】:
我正在学习 Python3 中的多重继承。我想知道为什么案例#1 有效,但案例#2 无效。这是我的代码 sn-ps。
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="myfriend@example.net",
street="Street",
city="City",
state="State",
code="0123")
这是脚本的输出。如果我在继承“Contact”和“AddressHolder”的“Friend”中仅使用 kwargs(案例#2)作为参数,则 Python 会出错。我已经测试了相同类型的没有继承的构造,除了对象,它工作得很好。
"""
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
>>>
"""
【问题讨论】:
标签: python-3.x typeerror multiple-inheritance keyword-argument