zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    最流行的javascript 代码规范
    jquery里阻止冒泡ev.stopPropagation()
    jquery里阻止冒泡ev.stopPropagation()
    响应式页面设计原理
    fromCharCode()的用法
    slice的用法
    java 反转数组
    java 一个数组的长度
    Java访问数组
    java 数组的定义
  • 原文地址:https://www.cnblogs.com/mtcnn/p/9424027.html
Copyright © 2011-2022 走看看