注意区分当前的 Python 版本是 2.X 还是 3.X,Python 3.X 在 super 的使用上较之 Python 2.X 有较大的变化;
0. super 的使用
-
使用 super 关键字调用父类:
# 如果不使用 super class A: def __init__(self): print("enter A") print("leave A") class B(A): def __init__(self): print("enter B") A.__init__(self) print("leave B") # 此时如果将 B 继承自 C class B(A): def __init__(self): print("enter B") C.__init__(self) print("leave B")
使用 super 关键字,则不必关注其继承的是哪个父类:
class B(A): def __init__(self): print("enter B") super(B, self).__init__() print("leave B")
1. Python 2.x
class Contact(object):
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contact.all_contacts.append(self)
class Friend(Contact):
def __init__(self, name, email, phone):
super(Friend, self).__init__(name, email)
self.phone = phone
Python 2.x 的环境下,对于需要被继承的父类,需要显式地将父类继承自 object 类,否则在子类使用 super(子类, self).__init__()
时会报 TypeError: must be type, not classobj.
这是因为 Python 2.x 中:
>> class A():
pass
>> type(A)
classobj
>> class A(object):
pass
>> type(A)
type
而且 Python 2.x 也并不将 classobj 视为 type.
当然子类中使用这样的语句也是可以的:
class Friend(Contact):
def __init__(self, name, email, phone):
Contact.__init__(self, name, email, phone)
self.phone = phone
<a href=“http://zhidao.baidu.com/link?url=uPkcvhMb4Cp4ddupz3xpswGQSkxoXpxqhZ58cB4tiITgHRQJXRpxkWejjNE5KYHtFuAVgArdPwzjZPDc5yYMsCZqcj8bNnzmIbROrhaON6O”, target="_blank">python super()用法遇到TypeError: must be type, not classobj
2. Python 3.x
class Contact:
all_contacts = []
def __init__(self, name, email):
self.name = name
self.email = email
Contact.all_contacts.append(self)
class Friend(Contact):
def __init__(self, name, email, phone):
super().__init__(name, email)
self.phone = phone