Python Dafa good--inheritance, polymorphism

Source: Internet
Author: User
Tags function definition

1. Inheritance of inheriting classes

One of the main benefits of object-oriented programming is the reuse of code, and one way to implement this reuse is through inheritance mechanisms.

A new class created through inheritance is called a subclass or derived class , and the inherited class is called a base class , parent class , or superclass .

Inheritance syntax

 class Derived classes name (base class name)

Some of the characteristics of inheritance in Python:

    • 1, if the constructor of the parent class is required in the subclass, the constructor method of calling the parent class needs to be displayed, or the constructor of the parent class is not overridden. Detailed description can be viewed: The Python subclass inherits the parent class constructor description.
    • 2. When calling a method of a base class, you need to prefix the class name of the base class with the Self argument variable. The difference is that you do not need to take the self argument when calling a normal function in a class
    • 3, Python always first looks for a method of the corresponding type, and if it cannot find the corresponding method in the derived class, it begins to look up one by one in the base class. (Find the method that was called in this class before you can find it in the base class).

If more than one class is listed in an inheritance tuple, it is called "Multiple inheritance."

Grammar:

The declaration of the derived class, similar to their parent class, inherits the list of base classes followed by the class name, as shown below

class subclassname (parentclass1[, ParentClass2, ...]):    ...
Method overrides

If the functionality of your parent's methods does not meet your needs, you can override the methods of your parent class in subclasses:

classParent:#defining the Parent class   defMyMethod (self):Print 'calling the parent class method' classChild (Parent):#Defining subclasses   defMyMethod (self):Print 'Calling Subclass Methods'C= Child ()#sub-class instancesC.mymethod ()#Subclass Call override Method
Private properties of the class

__private_attrs: Two underscores begin with, declaring that the property is private and cannot be used outside of the class or accessed directly. self.__private_attrswhen used in methods inside a class.

Methods of the class

Inside a class, you can define a method for a class using the DEF keyword, unlike a generic function definition, which must contain the parameter self and be the first argument

Private methods of the class

__private_method: Two underscores, declares that the method is a private method, and cannot be called outside of a class. Calling Self.__private_methods inside a class

classJustcounter:__secretcount= 0#Private VariablesPubliccount = 0#Exposing Variables     defcount (self): self.__secretcount+ = 1Self.publiccount+ = 1PrintSelf.__secretcountcounter=Justcounter () Counter.count () Counter.count ( )PrintCounter.publiccountPrintCounter.__secretcount  #error, instance cannot access private variable

Python does not allow instantiated classes to access private data, but you can use object._classname__attrname ( object name. _ Class Name __ Private property name ) to access the property

2. Polymorphic

Polymorphism refers to a class of things that have many forms, (an abstract class has more than one subclass, so the concept of polymorphism relies on inheritance)

(1) What is polymorphism (note: Polymorphism and polymorphism are two concepts)

Polymorphism refers to functions with different functions that can use the same function name, so that functions with different contents can be called with a function name. In an object-oriented approach, it is common to express polymorphism: sending the same message to different objects, and different objects having different behavior (that is, methods) when they are received. In other words, each object can respond to a common message in its own way. The so-called message, is called the function, the different behavior refers to the different implementation, namely executes the different function.

# Polymorphism : A calling method with different execution effects (polymorphism) def func (obj):    obj.run () func (Peo1) func (PIG1) func (D1)  #  peo1.run ()#  Pig1.run ()  #  polymorphism depends on: Inherit ##多态性: Define a unified interface,def#  obj This parameter has no type restriction and can pass in different types of values    # called logic is the same, execution of the result is not the same as func (peo1) func ( PIG1) func (D1)

(2).

Why use polymorphism (the benefit of polymorphism)

In fact, we can see from the above polymorphism example, we do not add the above new knowledge, that is, Python itself is to support polymorphism, so what is the advantage of doing so?
(1) Increased flexibility of the program
Status quo, regardless of the ever-changing object, the user is the same form to invoke, such as func (animal)
(2) Increased scalability of the program
By inheriting the animal class, a new class is created, and the user does not have to change their own code or use Func (animal) to invoke the

Note:

Polymorphism: Multiple forms of the same thing, animals divided into humans, pigs (in the definition of angle) Polymorphism: A method of invocation, different execution effect (polymorphism)

The advantage of polymorphism is that when we need to pass in dog, Cat, tortoise ... , we only need to receive the animal type, because dog, Cat, tortoise ... are animal types, and then follow the animal type. Because the animal type has run() methods, any type passed in, as long as it is a animal class or subclass, will automatically invoke the actual type of run() method, which is the meaning of polymorphism:

For a variable, we only need to know that it is a animal type, without having to know exactly what its subtype is, you can safely invoke run() the method, and the run() method is called on the animal, Dog, cat, or Tortoise object. Determined by the exact type of the object at run time, this is the true power of polymorphism: The caller just calls, regardless of the details, and when we add a animal subclass, simply make sure that the run() method is written correctly, regardless of how the original code is called. This is the famous "opening and shutting" principle:

Open to extensions: Allow new animal subclasses;

Closed for modification: You do not need to modify such functions as the dependent animal type run_twice() .

Python Dafa good--inheritance, polymorphism

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.