Examples: class inheritance in Python Object-Oriented Programming and python Object-Oriented Programming

Source: Internet
Author: User

Examples: class inheritance in Python Object-Oriented Programming and python Object-Oriented Programming

To create a class in python, you only need to define it.

class Cat:  pass

Just like this. By creating a subclass, We can inherit its parent class (superclass) method. Here, re-write cat.

class Cat:  name = 'cat'class A(Cat):  passprint A.name  # cat

Classic

We can also make A more inherited.

class Cat:  name = 'cat'class Dog:  name = 'dog'class A(Cat, Dog):  passprint A.name  # cat

What if the Cat class does not have the name attribute?

class Cat:  pass  ...print A.name  # dog

A will find the name attribute in other parent classes. What if the two parent classes inherit from the Animal class and the Animal class also has the name attribute?

class Animal:  name = 'animal'class Cat(Animal):  passclass Dog(Animal):  name = 'dog'class A(Cat, Dog):  passprint A.name  # animal

In this way, A will not find the name in the Dog class, but will find the name on the Animal, which is called A classic class. The class resolution sequence is a type of search with priority from left to right depth. That is, A-> Cat-> Animal-> Dog.

New category

There is also a way to create a class in python, that is, to use a new class (recommended), which inherits from the base class object. The search rules of the new class are sequential queries from left to right. That is, A-> Cat-> Dog-> Animal.

class Cat(object):  pass

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.