Python Tour: Object-oriented inheritance and derivation

Source: Internet
Author: User

A beginning knowledge of inheritance

When you write a class, you do not always start with whitespace. If you are writing a class that is just another special version of an out-of-the-box class, you can use inheritance to reduce code redundancy, which will "inherit" the attributes of the parent class to resolve code reuse issues

What is inheritance

Inheritance is a way to create a new class that can inherit one or more parent classes (Python supports multiple inheritance), which can also be called a base class or a superclass, and a new class is called a derived class or subclass.

When a class inherits from another class, he automatically obtains all the properties and methods of the other class, and the original class is called the parent class, and the new class is called a subclass. Subclasses inherit all the properties and methods of their parent class, and can also define their own properties and methods.

The inheritance of classes in Python is divided into: single inheritance and multiple inheritance

class # defining the parent class    Pass class # defining the parent class    Pass class # single inheritance, base class is ParentClass1, derived class is subclass    Pass class # Python supports multiple inheritance, separating multiple inherited classes    with commas Pass

View Inheritance

>>> subclass1.__bases__ #__base__只查看从左到右继承的第一个子类, __bases__ is to view all inherited parent classes (<class ' __main__. ParentClass1 ',,) >>> subclass2.__bases__ (<class ' __main__. ParentClass1 ';, <class ' __main__. ParentClass2 ' >)

Classic class and Modern class

1. Only in Python2 want $ The new class and the classic class, The unification of Python3 is a new kind of Class 2. In Python2, classes that do not explicitly inherit the object class, as well as subclasses of that class, are classic Class 3. In Python2, the class that inherits object explicitly, and the subclass of that class, are all modern Class 3. In Python3, whether or not to inherit OBJEC T, which inherits object by default, that is, all classes in Python3 are new class # about the difference between a new class and a classic class, we'll discuss later

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

>>> parentclass1.__bases__ (<class ' object ';,) >>> parentclass2.__bases__ (<class ' object ') ,)
two inheritance and abstraction (first abstract re-inheritance)

Inheritance describes the relationship between a subclass and a parent class, and what is a relationship of what. To find this relationship, you must first abstract and then inherit

Abstraction is the extraction of a similar or more like part.

An abstraction is divided into two levels:

1. Take the parts of Barack Obama and Lionel Messi, which are more like the two, into categories;

2. Extract the three categories of people, pigs, and dogs into a parent class.

The main function of abstraction is to classify categories (which can isolate concerns and reduce complexity).

Inheritance: is based on abstract results, through the programming language to achieve it, it must be through the process of abstraction, in order to express the abstract structure through inheritance.

Abstraction is just the process of analysis and design, an action or a skill that can be obtained by abstracting the class

Three-inheritance and re-usability
==========================the first part, for example, cats can: Meow meow, eat, drink, pull, dog can: bark, eat, drink, pull, sprinkle if we want to create a class for cats and dogs, then we need to implement all of their functions for cats and dogs, pseudo-code is as follows:#cats and dogs have a lot of the same contentclassCat:defmeow meow (self):Print 'Meow Meow'    defEat (self):#Do something    defDrink (self):#Do something    defPull (self):#Do something    defScatter (self):#Do somethingclassDog:defBarking (self):Print 'Meow Meow'    defEat (self):#Do something    defDrink (self):#Do something    defPull (self):#Do something    defScatter (self):#Do something==========================The second part of the above code is not difficult to see, eat, drink, pull, and Satan is the function of both cats and dogs, and we are the cat and the dog's class has been written two times. If you use the idea of inheritance, as follows: animals: Eat, drink, pull, sprinkle cats: Meow Meow (cat inherit the function of animals) Dog: Barking (dogs inherit the function of animals) pseudocode is as follows:classAnimals:defEat (self):#Do something    defDrink (self):#Do something    defPull (self):#Do something    defScatter (self):#Do something#write another class name in parentheses after the class, indicating that the current class inherits another classclassCat (animal):defmeow meow (self):Print 'Meow Meow'        #write another class name in parentheses after the class, indicating that the current class inherits another classclassDog (animal):defBarking (self):Print 'Meow Meow'==========================Part III#inherited code implementationsclassAnimal:defEat (self):Print("%s Eat"%self.name)defDrink (self):Print("%s Drink"%self.name)defshit (self):Print("%s Pull"%self.name)defpee (self):Print("%s Caesar"%self.name)classCat (Animal):def __init__(self, name): Self.name=name Self.breed='Cat'    defCry (self):Print('Meow Meow')classDog (Animal):def __init__(self, name): Self.name=name Self.breed='Dog'    defCry (self):Print('Barking')########## Execution #########C1= Cat ('Small White House of Little black Cat') c1.eat () C2= Cat ('Little Black Little white cat') C2.drink () D1= Dog ('Fat family's little skinny dog'd1.eat () A good example of using inheritance to reuse code
using inheritance to reuse code is a better example

In the process of developing a program, if we define a Class A and then want to create another class B, but most of the content of Class B is the same as Class A

It is not possible to write a class B from scratch, which uses the concept of class inheritance.

Create a new class B by inheriting it, let B inherit a A, a, a, all the attributes of ' heredity ' A (data attributes and function attributes), implement code reuse

classHero:def __init__(self,nickname,aggressivity,life_value): Self.nickname=Nickname Self.aggressivity=aggressivity Self.life_value=Life_valuedefMove_forward (self):Print('%s move forward'%self.nickname)defMove_backward (self):Print('%s Move Backward'%self.nickname)defMove_left (self):Print('%s move forward'%self.nickname)defmove_right (self):Print('%s move forward'%self.nickname)defAttack (Self,enemy): Enemy.life_value-=self.aggressivityclassGaren (Hero):PassclassRiven (Hero):PassG1=garen ('Bush LUN', 100,300) R1=riven (' Wen Wen', 57,200)Print(G1.life_value) r1.attack (G1)Print(G1.life_value)" "Run result 300243" "
View 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.

Note: A property reference such as G1.life_value will first find the Life_value from the instance and then go to the class and look for it in the parent class ... Until the top-most parent class.

Four derivative

Focus!!! : Look at Property lookup again

#inheritance: Subclasses can inherit some code from the parent class#derivation: Subclasses can define their own unique code, overwriting the code of the parent classclassFoo:defF1 (self):Print('foo.f1')    defF2 (self):Print('Foo.f2') self.f1 ()classBar (Foo):defF1 (self):Print('foo.f1') b=Bar () b.f2 ()#must be in accordance with this order to find: first go to their own name space to find f2--"did not go to their own class-" no more to the father to find#must be in accordance with this order to find: first go to their own name space to find f2--"did not go to their own class-" did not go to the parent class to find, so here is the bar class F1 # # #这就是派生#ResultsFoo.f2Foo.f1

Of course, subclasses can also add their own new properties or redefine them here (without affecting the parent class), and it is important to note that once you have redefined your own properties and have the same name as the parent, you will be able to invoke the new attributes when you call them.

Python Tour: Object-oriented inheritance and derivation

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.