Python and Duck type

Source: Internet
Author: User

Tag: Apply it to the specified IKE classic interface iter Rri collection

Part of the reference source:jasonding https://www.jianshu.com/p/650485b78d11# #s1

First, we introduce the following three features of object-oriented (OOP):

(1) Object-oriented programming has three main characteristics: encapsulation (encapsulation), Inheritance (inheritance), polymorphism (polymorphism). These three words are very common, everyone still remember as well!

(2) Encapsulation (encapsulation): Classes contain data and methods, and the data and methods are placed in a class to form the encapsulation.

(3) Inheritance (inheritance): Java is single-inheritance (this is different from C + +), meaning that a class can only inherit from a class, the inherited class is called the parent class (or the base class, or base class), the inheriting class is called the subclass. Inheritance in Java uses the keyword extends. However, a class can implement multiple interfaces, and multiple interfaces are separated by commas. Implements the interface using the keyword implements.

(4) Polymorphism (polymorphism): The most central idea of polymorphism is that a reference to a parent class can point to an object of a subclass, or a reference to an interface type can point to an instance of the class that implements the interface. Polymorphism is this because it is based on the fact that subclasses are the parent class!

(5) Some important notes about polymorphism:

    • When invoking a method using polymorphic methods, first check if there is a method in the parent class, if there is no compile error, if any, then call the subclass override (override) "If overridden" this method, if not overridden, or invoke the method inherited from the parent class.
    • Two types of coercion type conversions:
      1. Up type conversion (upcast): Converts a subtype reference to a parent type reference. For up-type conversions, the display designation is not required.
      2. Down type conversion (downcast): Converts a parent type reference to a subtype reference. For a down type conversion, you must display the specified. The principle of the downward type conversion: The parent type refers to who can convert to WHO.
    • Polymorphism is a run-time behavior, not a compile-time behavior! During compilation it only knows that it is a reference, and only when it is executed does the reference know who it is pointing to. This is known as "soft binding".
    • Polymorphism is an important technique that allows programmers to "separate things from changes and things that do not change."
Duck Type:

Calling different subclasses will produce different behaviors without having to know exactly what this subclass is actually, which is an important application scenario for polymorphism. And in Python, because the duck type (duck typing) makes its polymorphism not so cool.
Duck type is a style of dynamic type. In this style, an object's valid semantics are determined not by inheriting from a particular class or implementing a particular interface, but by the "collection of current methods and properties". The concept comes from the duck test presented by James Whitcomb Riley, "duck test" can be said: "When you see a bird walking like a duck, swimming like a duck, barking like a duck, then this bird can be called a duck." ”
In duck type, the focus is not on the type of the object itself, but how it is used. For example, in a language that does not use duck type, we can write a function that takes an object of type "Duck" and invokes its "walk" and "call" methods. In a duck-type language, such a function can accept an arbitrary type of object and invoke its "walk" and "call" methods. If the method that needs to be called does not exist, a run-time error is raised. Any object with such a correct "walk" and "call" method can be accepted by the function, which leads to the above expression, and hence the name of this type of decision.
duck types typically benefit from not testing the types of parameters in methods and functions, but rely on documentation, clear code, and testing to ensure proper use.

Duck typing this concept comes from the American Indiana poet James Whitkom Lelly (James Whitcomb riley,1849-
1916) Verse: "When I see a bird that walks like a duck and swims like a duck and quacks as a duck, I call that bird a duck."
First on the code, but also from the Internet is a classic case:

1 classDuck ():2     defWalk (self):3         Print('I Walk Like a duck')4     defSwim (self):5         Print('I swim like a duck')6 7 classPerson ():8     defWalk (self):9         Print('This one walk like a duck') Ten     defSwim (self): One         Print('This mans swim like a duck')

It is clear that the Person class has Duck the same method as the class, when there is a function call Duck class, and takes advantage of two methods walk() and swim() . We pass in Person classes as well as run, and the function does not check the type of the object, Duck as long as he owns walk() and swim() methods, it can be called correctly.
For example, if an object implements a __getitem__ method, then the Python interpreter will use it as one, so that the collection object can be used to slice, get the child, and so on, if an object implements the __iter__ and next method, Python will think it is a iterator, you can get the individual subkeys on this object by looping through them.

Polymorphism in Python

The duck type in Python allows us to use any object that provides the required method without forcing it to become a subclass.
Since Python is a dynamic language, when you define a method in a base class and a base class, and write several subclasses that inherit the base class, because Python does not specify the type of the variable when it defines the variable, the interpreter infers the variable type based on the content of the variable (that is, the type of the variable depends on the object being associated). This makes Python polymorphic unlike in C + + or Java, where a base class type variable is defined and the details of a specific subclass are hidden.

Take a look at the following examples and instructions:

1 classAudioFile:2     def __init__(self, filename):3         if  notFilename.endswith (self.ext):4             RaiseException ("Invalid file Format")5Self.filename =filename6 7 classMp3file (AudioFile):8ext ="mp3"9     defPlay (self):Ten         Print("Playing {} as mp3". Format (self.filename)) One  A classWavfile (AudioFile): -ext ="wav" -     defPlay (self): the         Print("Playing {} as WAV". Format (self.filename)) -  - classOggfile (AudioFile): -ext ="ogg" +     defPlay (self): -         Print("Playing {} as Ogg". Format (self.filename)) +  A classFlacfile: at     """ - Though Flacfile class doesn ' t inherit AudioFile class, - It also has the same interface as three subclass of AudioFile. -  - It is called duck typing. -     """ in     def __init__(self, filename): -         if  notFilename.endswith (". FLAC"): to             RaiseException ("Invalid file Format") +Self.filename =filename -  the     defPlay (self): *         Print("Playing {} as FLAC". Format (Self.filename))
In the above code, MP3FileWavFileOggFileThree types inherit the AudioFileThis base class, while FlacFileNo extension AudioFile, but you can interact with it in Python using the exact same interface.
Because any object that provides the correct interface can be used interchangeably in Python, it reduces the need for a polymorphic generic superclass. Inheritance can still be used to share code, but if all shared are public interfaces, the duck type is all that is needed. This reduces the need for inheritance and also reduces the need for multiple inheritance; Often, when multiple inheritance seems to be an effective scheme, we only need to use duck types to simulate one of several superclass (the definition and the same superclass interface and implementation).

Python and Duck type

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.