Python ()-object-oriented three major features----inheritance

Source: Internet
Author: User


Inherited:

Inheritance is a way of creating new classes,
In Python, a new class can inherit one or more parent classes (base or superclass), and the new class is the inherited class (derived class or subclass)


Humans and dogs have the same attributes, extract a __init__ method, and put some common attributes in this method.
Humans and dogs in the same way, extracted a def func (): method, put some common methods in this method

Single inheritance and multiple inheritance
Class Par1:    passclass Par2:    passclass Sub1 (Par1):    passclass Sub2 (par1,par2):    pass#__base__ View only the first parent class from left to right, and __bases__ view all of the parent class print (sub1.__bases__) # (<class ' __main__. Par1 ';,) print (sub2.__bases__) # (<class ' __main__. Par1 ';, <class ' __main__. Par2 ' >)------------------------------------print (par1.__base__) #<class ' object ' >

  

If you do not specify a base class, the Python class inherits the object class by default, and the object class is the base class for all classes , and it provides implementations of some common methods, such as __str__

 

Class Par1:    def __init__ (self,name):        self.name = name    def __str__ (self):        return SELF.NAMEP = Par1 (' Kitty ') print (p) # kitty

  

Class Foo1:def __init__ (self,name):     # Self is f object self.name = Namedef __str__ (self): return self.nameclass Foo2 (Foo1): A = 1f = Foo2 (' Kitty ')     #Foo2中没有__init__函数, go to the base class and then pass in the parameter print (f.name)     # kitty

  

Inheritance and abstraction:

There is no human, just a lot of specific people object, and then all the people into the abstract (zoned into) a class, only the concept of human
So: Abstraction is from bottom to top
Inherit from top down


Inheritance and re-usability:

The purpose of inheritance is to reduce the duplication of code


Like what:

Want to create a class B, but found that the properties of Class B are mostly the same as Class A, let B inherit the properties of a, save the code

Tip: Use existing classes to create a new class, so that you reuse the existing software part of the set of most of the programming effort, which is often said that the software reuse, not only can reuse their own classes, but also inherit others, such as the standard library, to customize the new data types, This is greatly shorten the software development cycle, for large-scale software development, it is of great significance.

Classic and Modern classes:

Python3 are new classes (the new class inherits by default Object class Foo (object): = = class Foo:)

Coexistence of classic and modern classes in Python2

    • Class Foo: A classic class
    • Class Foo (object): A new class

Diamond Inheritance:
    • Classic class : depth First , that is, one line to go to the end, and then to other lines
    • New class : The one-way walk to the remaining last parent class to stop, and then to find other lines, the last line went to the tail
Classic Class Inheritance Order:

Depth first

New Class Inheritance Order:

Breadth First:

If I find B, I'll go to C C and find E-E and I'm going to find F-F. Because F can't find the D single line
=====================================================
Python2: The most primitive plus object, will inherit object in the future
======================================

See again:

classD:def __init__(self):Print('D')classC (D):def __init__(self):Print('C') Super ().__init__()classB (D):def __init__(self):Print('b') Super ().__init__()classA (b,c):def __init__(self):Print('a') Super ().__init__()#MROA =A ()Print(A.mro ())##结果如下:abcd[<class '__main__. A', <class '__main__. B', <class '__main__. C', <class '__main__. D', <class 'Object'>] and the MRO order as breadth first (super only in the new Class) in multi-inheritance, super is not only looking for the current class's parent class, but based on the MRO order, from the A node, based on the breadth of precedence to find the next class

Derived


Derived:

Class A: # base class (extracts the common attributes of dogs and humans) def __init__ (Self,name, Aggressivity, Life_value): #里面的self是对象self. Name = nameself.aggressivity = Aggressivityself.life_value = Life_valuedef eat (self):p rint (' A eating ') class Dog (a): # Define a Dog class Def __init__ (Self,name, aggressivity, Life_value,breed,): #派生一个__init__方法 #a.__init__ (Self,name, aggressivity, Life_value): Class name. __init__ (parameter) super (). __INIT__ (name, aggressivity, Life_value) #调用基类__init__方法: Super (). __INIT__ () Self.breed = breed # Every dog has its own breed; def bite (self,people): Attribute & Method Not in parent class people.life_value-= Self.aggre Ssivitydef Eat (self): #重新定义eat (derived) a.eat (self) #如果想加上父类的方法: A.eat (object) print (' Dog eating ') class person (a): # defines a human de F __init__ (Self,name, Aggressivity, Life_value,money): #派生super (). __init__ (name, aggressivity, Life_value) #调用基类__in it__ Method Self.money = Moneydef attack (self,dog):d og.life_value-= Self.aggressivitydef get_weapon (self,weapon_obj): if        Self.money > Weapon_obj.price:self.money-= Weapon_obj.price # Kim's boss pays for weapons self.weapon = weapon_obj # Gold boss equipment hit dog stick self.aggressivity + = weapon_obj.aggr # Gold Boss's attack increased Jin = Perso N (' Jin ', 250,250,100) dog = Dog (' Cool dog ', 33, 50, ' Tibetan Mastiff ') print (jin.name) # jinprint (Jin.money) # 10 0print (dog.name) # Cool dog Print (dog.breed) # Tibetan Mastiff dog.eat () # a eating# dog eating-------------------A. Eat (dog) #A eating class name. Method Name (object name)--------------------------------super (Dog,dog). Eat () #A eating Super (class name, object name) super is out there.     Parameter ======================================== must be transmitted.

  

Derived methods and properties:
1. Add the parent class to the subclass
2. If you call the methods and properties of the parent class again

Parent class. __init__ (self, parameter ...)

Super () __init__ (Parameters ...)? Call names

Super (subclass name, object) when super is used outside the class. Properties
  

Summary:

Subclasses have, with their own, no use of the parent class
Subclasses have, the parent class has, still want to use the parent class:
Classic class: Parent class. __INIT__ (self, parameter ...) parent class. Method Name (object)
New class: Super (). __init__ (Parameters ...) parent class. Method Name (object)

Under normal circumstances, super is satisfied
Names call the parent class's method parent class. Method (self)-Self is the object of the child class


Example: printing results

classFoo:def __init__(self): (the object itself, the object has func ()) Self.func ()deffunc (self):Print('Parent Class')classSon (Foo):deffunc (self):Print('sub-class') s=Son ()#sub-class----------------Print(Son.mro ()) a way to view the inheritance order for a new class:Print(class name. MRO ()) [<class '__main__. Son', <class '__main__. Foo', <class 'Object';]

Python ()-object-oriented three major features----inheritance

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.