Inheritance and polymorphism in Python

Source: Internet
Author: User

Inherited

The way that inheritance behaves:

class Animal ():     Pass class Cat (Animal):  #Animal is the cat's parent class, or it can be said to be the base class    passprint(cat.  __bases__)# View all the cat's parent classes
Single inheritance

A class has only one parent class

Dogs and birds are animals, both have the ability to eat and drink, but swimming is a dog's special skills, flying birds ' special skills, can only be extended in this class

How a unique method in a subclass implements

Implements a unique method in a subclass that has a unique attribute for that subclass? I had a little teddy, and I gave him a name, but the bird didn't have this property.

classAnimal ():def __init__(self,kind): Self.kind=KinddefEat (self):Print('Eat ...')    defDrink (self):Print('Drink ...')classDog (Animal):def __init__(self,kind,name):#animal.__init__ (self,kind) #为继承的父类中的属性初始化赋值Super ().__init__(kind)#using Super to find the parent class has the same effect as the sentence.Self.name = Name#Initializes an assignment for properties unique to this class, derived properties    defSwimming (self):Print('Dog Swimming')classBird (Animal):defFly (self):Print('Bird Flying')    defEat (self):Print('Bird Eat') B1= Bird ('Sparrow') B2= Dog ('Tiddy','Judy')Print(B1.kind)Print(B2.name)
how a unique property in a subclass is implementedMultiple inheritance

A class has more than one parent class

classA ():defFun (self):Print('AAA')classB ():defFun (self):Print('BBB')classC ():defFun (self):Print('CCC')classD (A,B,C):#Inherit A,b,c    PassD=D () d.fun ()#AAA---> Call the Fun method in Class A, according to the inheritance order a
Simple Multiple InheritanceDiamond Inheritance
‘‘‘
A
B C

D E
F
F Inheritance de,d inheritance B,e inheritance C,BC a
The order is: F->d->b->e->c->a
‘‘‘
#another question, about Super,super really looking for the parent class? #class A ():#def Fun (self):#print (' a ')#class B (A):#def Fun (self):#super (). Fun () #--> find C#print (' B ')#class C (A):#def Fun (self):#super (). Fun () #--> find a#print (' C ')#class D (b,c): #继承B, C#def Fun (self):#super (). Fun () #--> looking for b#print (' d ')#d = d ()#D.fun () #打印结果是 a C b d##以菱形多继承为例, the discovery is based on the priority algorithm found in the upper level
Super Questioninterface classes and abstract classes

There is no interface concept in Python, and interface classes and abstract classes are concepts in Java that are designed to develop a specification

Neither the interface class nor the abstract class can be instantiated

# Interface Class #      support multiple inheritance, all methods in the interface class cannot be implemented #  abstract class #      does not support multiple inheritance, methods in abstract classes can be implemented
Interface class
 from Import Abstractmethod,abcmeta # creating a canonical class class Payment (Metaclass=abcmeta):# Specifies the meta-class     @abstractmethod    def Pay (self): Pass  # classes that inherit from this class must implement this method
Multiple inheritance of interface classes

Thinking:

How to define three classes with no duplication of code: 1. The bird-------will fly, will go 2. The dog----can swim, walk 3. Ducks---can swim, fly, walk.

 fromAbcImportAbstractmethod,abcmetaclassFly_animal (metaclass=Abcmeta): @abstractmethoddefFly (self):PassclassWalk_animal (metaclass=Abcmeta): @abstractmethoddefWalk (self):PassclassSwim_animal (metaclass=Abcmeta): @abstractmethoddefSwim (self):PassclassBird (Fly_animal,walk_animal):PassclassDog (Walk_animal,swim_animal):PassclassDuck (Walk_animal,swim_animal,fly_animal):Passb= Bird ()#error Typeerror:can ' t instantiate abstract class Bird with abstract methods fly, walk#the class that inherits the canonical interface class must implement the method of adding @abstractmethod adorner, otherwise the error
multiple inheritance of interface classesAbstract class

Rules only use single inheritance

Implement an abstract class

Import ABC# creates a canonical class Payment (metaclass=abc. Abcmeta):# Specifies the meta -Class @abc . Abstractmethoddef Pay (self):pass # classes that inherit this class must implement this method
Polymorphic

Python natively supports polymorphism

Duck type

Inheritance and polymorphism in Python

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.