Python 面向对象 —— super 的使用(Python 2.x vs Python 3.x)

注意区分当前的 Python 版本是 2.X 还是 3.X,Python 3.X 在 super 的使用上较之 Python 2.X 有较大的变化;

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

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
原文地址:https://www.cnblogs.com/mtcnn/p/9424028.html