Python object-oriented feature Summary

Source: Internet
Author: User
Tags export class

Abstraction is the art of hiding redundant details. In the object-oriented concept, the direct representation of abstraction is usually a class. Python basically provides all the elements of the object-oriented programming language. If you have mastered at least one object-oriented language, it is quite easy to use Python for object-oriented programming.

I. Encapsulation

The term Object in Object-Oriented Programming can basically be seen as a collection of data (features) and a series of methods that can access and operate the data. In the traditional sense, "program = Data Structure + algorithm" is encapsulated and "hidden" and simplified to "program = Object + message ". Objects are instances of classes, and class abstraction needs to be encapsulated. Encapsulation allows the caller to directly use the object without worrying about how the object is constructed.

A simple Python class is encapsulated as follows:

Encapsulation_metaclass _ = type # confirm to use the new class Animal: def _ init _ (self): # constructor. After an object is created, this method self is called immediately. name = "Doraemon" print self. name def accessibleMethod (self): # The binding method exposes print "I have a self! Current name is: "print self. name print "the secret message is:" self. _ inaccessible () def _ inaccessible (self): # private methods are not publicly available. print "U cannot see me... "@ staticmethod def staticMethod (): # self. accessibleMethod () # You cannot directly call an instance method in a static method to directly throw an exception print "this is a static method" def setName (self, name): # accesser function self. name = name def getName (self): # accessors return self. name name = property (getName, setName) # readable and writable attribute

 

The simple sample code above shows that the class in Python contains the main elements of the general object-oriented programming language, such as the constructor, binding method, static method, and attribute. If you go deeper, it can also be found that Python has many "advanced" Object-Oriented themes, such as iterators, reflection, and features, and provides the direct construction elements of encapsulation.

 

Ii. Inheritance 1. class inheritance

The direct sense of inheritance is that it is a behavior of reusing code. Inheritance can be understood as it is based on ordinary classes to establish a special class object, subclass and its inherited parent class is the relationship of IS-A. A simple and classic example is as follows:

Inheritance_metaclass _ = type # confirm to use the new class Animal: def _ init _ (self): self. name = "Animal" def move (self, meters): print "% s moved % sm. "% (self. name, meters) class Cat (Animal): # Cat is the subclass of Animal def _ init _ (self): # override the constructor self of the superclass. name = "Garfield" # def move (self, meters): # rewrite the superclass binding method # print "Garfield never moves more than 1 m. "class RobotCat (Animal): def _ init _ (self): # override the superclass constructor self. name = "Doraemon" # def move (self, meters): # rewrite the superclass binding method # print "Doraemon is flying. "obj = Animal () obj. move (10) # output: Animal moved 10m. cat = Cat () cat. move (1) # output: Garfield moved 1m. robot = RobotCat () robot. move (1000) # output: Doraemon moved 1000 m.

 

An obvious feature is that Python's Object-oriented Inheritance feature is based on classes, which is easier to organize and write code than javascript's prototype-based inheritance, it is easier to accept and understand.

Ps: in the past few days, the TypeScript developed by the great gods of Anders has turned out to be class-based in terms of its language specifications:

TypeScript-SimpleInheritanceclass Animal {    constructor(public name) { }    move(meters) {        alert(this.name + " moved " + meters + "m.");    }}class Snake extends Animal {    constructor(name) { super(name); }    move() {        alert("Slithering...");        super.move(5);    }}class Horse extends Animal {    constructor(name) { super(name); }    move() {        alert("Galloping...");        super.move(45);    }}var sam = new Snake("Sammy the Python")var tom: Animal = new Horse("Tommy the Palomino")sam.move()tom.move(34)

 

It seems that the inherited class-based language is not very easy to implement OO readability and programming experience. It is said that javascript is the most preferred language for coders and the language that has sprayed a maximum of f ** k.

2. Multi-Inheritance

Unlike C #, Python supports multi-class inheritance (C # can inherit from multiple interfaces, but can inherit from a maximum of one class ). Multiple inheritance mechanisms are sometimes useful, but they make things more complex. An example of multi-inheritance is as follows:

MultInheritance_metaclass _ = type # confirm to use the new class Animal: def eat (self, food): print "eat % s" % food class Robot: def fly (self, kilometers ): print "flyed % skm. "% kilometers class RobotCat (Animal, Robot): # inherits from multiple superclasses def _ init _ (self): self. name = "Doraemon" robot = RobotCat () # print robot, a bot that can eat and fly. namerobot. eat ("cookies") # eatrobot inherited from animals. fly (10000000) # fly inherited from machines

 

As you can see, the benefits of Multi-inheritance are obvious. We can easily reuse code to construct a type in a way similar to "Combination.

Note that if a method inherits from multiple superclass, you must be careful about the sequence of the inherited superclass (or base classes:

MultInheritance_metaclass _ = type # confirm to use the new class Animal: def eat (self, food): print "eat % s" % food def move (self, kilometers ): # Animal move method pass class Robot: def move (self, kilometers): # machine move method print "flyed % skm. "% kilometers class RobotCat (Animal, Robot): # inherit from multiple superclasses. If the method name is the same, pay attention to the inheritance sequence # class RobotCat (Robot, Animal ): def _ init _ (self): self. name = "Doraemon" robot = RobotCat () # print robot, a bot that can eat and fly. namerobot. eat ("cookies") # eatrobot inherited from animals. move (10000000) # The move method is inherited from the machine, but because of the inherited order, this method directly inherits the automatic object and passes it out.

 

We implement a move method with the same name for each animal and machine, but the output varies according to the inherited sequence, the Order in which Python accesses superclasses when looking for a given Method or feature is called MRO (Method Resolution Order, Method determination Order ).

Iii. Polymorphism

Polymorphism means that the same operation can be performed on different objects, but they may present results in multiple forms. In Python, polymorphism is used when you do not know the object type, but need to do something about it.

Two sample codes that can directly describe polymorphism are as follows:

1. Method Polymorphism
Method-Polymorphism_metaclass _ = type # determine to use the new class calculator: def count (self, args): return 1 calc = calculator () # custom type from random import choiceobj = choice (['hello, world', [, 3], calc]) # obj is the type returned randomly. Uncertainty # print type (obj) print obj. count ('A') # method Polymorphism

 

For a temporary object obj, it is obtained by using the Python random function. You can call the count method for calculation if you do not know the specific type (string, tuples, or custom type, we don't care about who (which type) does count implement it.

There is something called "duck type (duck typing)", also speaking of polymorphism:

DuckTyping_metaclass _ = type # confirm to use the new class Duck: def quack (self): print "Quaaaaaack! "Def feathers (self): print" The duck has white and gray feathers. "class Person: def quack (self): print" The person imitates a duck. "def feathers (self): print" The person takes a feather from the ground and shows it. "def in_the_forest (duck): duck. quack () duck. feathers () def game (): donald = Duck () john = Person () in_the_forest (donald) in_the_forest (john) game ()

For the in_the_forest function, the parameter object is a duck type, which implements method polymorphism. However, we actually know that the Person type and Duck are completely different from each other in terms of strict abstraction.

2. Operators are also Polymorphism
Operator-Polymorphismdef add (x, y): return x + yprint add (1, 2) # output 3 print add ("hello,", "world") # output hello, worldprint add (1, "abc") # throw an exception TypeError: unsupported operand type (s) for +: 'int' and 'str'

 

In the above example, it is obvious that the addition operator of Python is "polymorphism". Theoretically, the add method we implement supports arbitrary addition objects, however, we do not need to care about the specific types of the two parameters x and y.

Of course, one or two sample codes cannot fundamentally describe polymorphism. It is generally believed that the most valuable and undervalued feature of object-oriented systems is polymorphism. The implementation of polymorphism is related to the virtual function Address binding of the subclass. The effect of polymorphism is actually related to the dynamic binding of the function address during runtime. In C #, there are usually two methods to implement polymorphism: rewrite and overload. From the above two sections of code, we can analyze that the implementation of polymorphism in Python can also be understood as rewrite and overload in disguise. Many built-in functions and operators in Python are polymorphism.

No.: in C #, we are familiar with Interface and polymorphism. when processing a polymorphism object, we only need to care about its Interface (or "Protocol ") you do not need to explicitly specify a specific implementation type, which is also the basis for interface-oriented (abstract) in IoC without relying on specific implementation programming. Unfortunately, there is no Interface (with abstract classes) in Python ). In Specification of TypeScript, the concept of Interface is introduced:

TypeScript-Interfaceinterface Friend {    name: string;    favoriteColor?: string;}function add(friend: Friend) {    var name = friend.name;}add({ name: "Fred" });  // Okadd({ favoriteColor: "blue" });  // Error, name requiredadd({ name: "Jill", favoriteColor: "green" });  // Ok

 

In the TypeScript language specification, the Interface is defined as the named object type (Programmers can give names to object types; we call named object types interfaces .). It is directly equivalent to the following Ojbect Type:

var Friend: () => {    name: string; favoriteColor?: string;};

The above javascript code of the Object Type in Playgound is as follows:

var Friend;

In the TypeScript programming specification document, the Interface is described as follows:

Interfaces provide the ability to give names to object types and the ability to compose existing named object types into new ones.
Interfaces have no run-time representation-they are purely a compile-time construct. interfaces are special useful for documenting and validating the required shape of properties, objects passed as parameters, and objects returned from functions
.

Interfaces can be inherited from interfaces:

TypeScript-InterfaceInheritInterfaceinterface Mover{    move(): void;    getStatus(): { speed: number; };}interface Shaker{    shake(): void;    getStatus(): { frequency: number; };}interface SimpleMover extends Mover{}interface MoverShaker extends Mover, Shaker{    getStatus(): { speed: number; frequency: number; };}

 

Let's try to make the class inherit from Interface:

TypeScript-ClassInheritInterfaceinterface Mover{    move(): void;}class SimpleMover  extends Mover{    move() {alert("move")    }}var mover=new SimpleMover();mover.move();

 

Practice has proved that classes cannot inherit interfaces: A export class may only extend other classes, Mover is an Interface.

Do you know the differences between interfaces in TypeScript and those we know and understand? The same noun Interface has different meanings in different contexts. It seems silly, but it is almost impossible to compare learning with using languages.

 

Refer:

Http://www.python.org/

Http://zh.wikipedia.org/wiki/Duck_typing

Http://typescript.codeplex.com/

Http://www.typescriptlang.org/Playground/

Http://www.nczonline.net/blog/2012/10/04/thoughts-on-typescript/

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.