当前位置:
首页 >
Python 面向对象 —— super 的使用(Python 2.x vs Python 3.x)
发布时间:2025/4/14
38
豆豆
生活随笔
收集整理的这篇文章主要介绍了
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 = nameself.email = emailContact.all_contacts.append(self)class Friend(Contact):def __init__(self, name, email, phone):super(Friend, self).__init__(name, email)self.phone = phonePython 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 = phonepython super()用法遇到TypeError: must be type, not classobj
2. Python 3.x
class Contact:all_contacts = []def __init__(self, name, email):self.name = nameself.email = emailContact.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/9424027.html
总结
以上是生活随笔为你收集整理的Python 面向对象 —— super 的使用(Python 2.x vs Python 3.x)的全部内容,希望文章能够帮你解决所遇到的问题。
- 上一篇: 其实吧,微信就是已经用电脑上线,第二天消
- 下一篇: Python内存数据库/引擎