Python note Six (three main features of object-oriented)

Source: Internet
Author: User

Three main features of a class: inherited polymorphic Encapsulation

1. What is inheritance

Inheritance is a way to create a new class, in Python, a new class can inherit one or more parent classes, which can be called a base class or a superclass, and a new class is called a derived class or subclass.

Why is there inheritance? Solves the problem of redundancy in the code.

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

Parent Class--superclass class
Son class --Subclass derived class

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

#__base__ only view the first parent class inherited from left to right, __bases__ is to view all inherited parent classesPrint(SubClass2.__base__)#>>><class ' __main__. ParentClass1 ' >Print(SubClass1.__bases__)#>>> (<class ' __main__. ParentClass1 ';,)Print(SubClass2.__bases__)#>>> (<class ' __main__. ParentClass1 ';, <class ' __main__. ParentClass2 ' >)#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 ';,)
2, inheritance and abstraction (first abstract and then inherit)

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

3. Inheritance and re-usability

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

classAnimal:" "Both humans and dogs are animals, so create a animal base class" "    def __init__(self, name, aggressivity, life_value): Self.name= Name#both man and dog have their nicknames;Self.aggressivity = aggressivity#both man and dog have their own attack power;Self.life_value = Life_value#both man and dog have their own health value;    defEat (self):Print('%s is eating'%self.name)classDog (Animal):PassclassPerson (Animal):PassEgg= Person ('Egon', 10,1000) HA2= Dog ('Erlengzi', 50,1000) Egg.eat () ha2.eat ()

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.

4. Derivation

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.

In subclasses, the new function property of the same name, when editing functions within the function, it may be necessary to reuse the same function function in the parent class, should be used to call the normal function, namely: class names. Func (), at this point is the same as calling the normal function, so even the self parameter to pass the value.

The relationship between the derived class and the base class is established through inheritance, which is a ' yes ' relationship, such as a horse in a white horse and a human being an animal.

when there are many identical functions between classes, extracting these common functions into a base class is better with inheritance, for example, a professor is a teacher .

classAnimal:def __init__(self, name, HP, DPS): Self.name=name SELF.HP=HP Self.dps=DPSdefEat (self):Print('%s took the medicine.'%self.name)classPerson (Animal):def __init__(self, name, HP, Dps,sex):#First form: animal.__init__ (self, name, HP, DPS)        #Another method is the equivalent of super (person,self) __init__ (Name,hp,dps), person,self is the Python interpreter automatically addedSuper ().__init__(Name,hp,dps) self.sex= Sex#Derived Properties    defAttack (Self,dog): dog.hp-=Self.dpsPrint('%s hit%s,%s lost the blood of%s, the remaining%s points of blood'%(Self.name, Dog.name, Dog.name, Self.dps, dog.hp))classDog (Animal):def __init__(Self,name,hp,dps,kind): Super ().__init__(name, HP, DPS) Self.kind= Kind#Derived Properties    defBite (Self,person): person.hp-=Self.dpsPrint('%s hit%s,%s lost the blood of%s, the remaining%s points of blood'%(Self.name, Person.name, Person.name, Self.dps, PERSON.HP)) Alex= Person ('Alex', 250, 5,'N /A') HA2= Dog ('Husky', 15000,200,'Tibetan Mastiff')Print(Alex.)__dict__)Print(HA2.__dict__) Ha2.eat () alex.eat () Ha2.bite (Alex) Alex.attack (HA2)#>>>{' name ': ' Alex ', ' HP ': $, ' DPS ': 5, ' sex ': ' N/A '}#>>>{' name ': ' Husky ', ' hp ': 15000, ' DPS ': $, ' kind ': ' Tibetan Mastiff '}#>>> Husky's taking medicine.#>>>alex the pills.#>>> Husky hit the alex,alex dropped 200 blood, the remaining 50 points of blood

Python note Six (three main features of object-oriented)

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.