Python Object-oriented--super (Python 2.x vs Python 3.x) __python

Source: Internet
Author: User

Note whether the current Python version is 2.X or 3.x,python 3.X has a greater change in the use of super than 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:
    def __init__ (self, name, email, phone):
        Super (Friend, self). __init__ (name, email)
        Self.phone = Phone

In the Python 2.x environment, for a parent class that needs to be inherited, you need to explicitly inherit the parent class from the object class, otherwise use super (subclass, Self) in the subclass. __INIT__ () will be reported Typeerror:must is type, not classobj.

This is because of the Python 2.x:

>> Class A ():
       pass
>> type (a)
classobj

>> Class A (object):
Pass >> type (A)
type

and Python 2.x does not treat classobj as type.

Of course, it is also possible to use such a statement in a subclass:

Class Friend:
    def __init__ (self, name, email, phone):
        contact.__init__ (self, name, email, phone)
        Self.phone = Phone

Python super () usage encounters 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
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.