Python (21)

Source: Internet
Author: User

Polymorphism and polymorphism

Many people like to confuse the two, and then think about the solution, in fact, as long as the separate look, it will be very clear

1.1 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. Sequence types are available in several forms: string, list, and tuple.

2. Animals in various forms: human, dog, pig

Import Abcclass Animal (METACLASS=ABC. Abcmeta): #同一类事物: Animal    @abc. Abstractmethod    def talk (self):        passclass People (Animal): #动物的形态之一: People    def Talk (self):        print (' Say hello ') class Dog (Animal): #动物的形态之二: The dog    def talk (self):        print (' Say Wangwang ') class Pig (Animal): #动物的形态之三: Pig    def talk (self):        print (' Say Aoao ')

3. There are several forms of files: text files, executable files

Import Abcclass File (METACLASS=ABC. Abcmeta): #同一类事物: File    @abc. Abstractmethod    def click (self):        passclass text (file): #文件的形态之一: Text file    def Click (self):        print (' Open file ') class Exefile (file): #文件的形态之二: Executable    def click (self):        print (' Execute file ' ‘)

1.2 Polymorphism

What is polymorphism (it is important to note that polymorphism and polymorphism are two kinds of concepts.) )

Polymorphism refers to functions with different functions that can use the same function name, so that functions can be called with a function name in different functions.

In the object-oriented approach, it is generally said that polymorphism : Sending the same message to different objects (!!!) Obj.func (): Is the method func that called obj, also known as a message func sent to obj, and different objects have 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.

For example: Teacher. The bell rang (), the student. The bell rang (), the teacher performed the off-duty operation, the students performed the school operation, although the two messages, but the effect of the implementation of different

Polymorphism is divided into static polymorphism and dynamic polymorphism

Static polymorphism: If any type can be operated with operator +

Dynamic polymorphism: The following

1.

2.

>>> def func (animal): #参数animal就是对态性的体现 ...     Animal.talk () ... >>> people1=people () #产生一个人的对象 >>> pig1=pig () #产生一个猪的对象 >>> Dog1=dog () # Produce a Dog object >>> func (people1) say hello>>> func (PIG1) say aoao>>> func (dog1) say Wangwang

3.

>>> def func (f): ...     F.click () ... >>> t1=text () >>> e1=exefile () >>> func (T1) Open file>>> func (E1) Execute file

We can also say that polymorphism is ' an interface (function Func), a variety of implementations (such as F.click ()) '

Two reasons to use polymorphism (the benefit of polymorphism)

In fact, we can see from the above polymorphism example, we have not added any new knowledge, that is, Python itself is to support polymorphism, what is the benefit 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

>>> class Cat (Animal): #属于动物的另外一种形态: Cat     ... Def talk (self): ...         Print (' Say Miao ') ... >>> def func (animal): #对于使用者来说, your code doesn't have to be changed     at all ... Animal.talk () ... >>> cat1=cat () #实例出一只猫 >>> func (CAT1) #甚至连调用方式也无需改变, you can call the cat talk function say Miao " In this way we have added a new form of cat, which is generated by the cat class CAT1, and the user can do so without having to modify their own code at all. Call Cat1 's Talk method in the same way as humans, dogs, and pigs, called Func (CAT1) "
Two binding methods and non-binding methods

The functions defined in the class are divided into two main categories:

One: The binding method (which is bound to whom, who calls it automatically passes itself as the first parameter):

1. Methods to bind to a class: The method of decorating with the Classmethod adorner.

Tailor-made for the class

Class. Boud_method (), which automatically passes a class as the first parameter

(The object can also be called, but the class is still passed in as the first parameter)

2. Methods bound to an object: There is no way to decorate it with any adorner.

Tailor-made for objects

Object . Boud_method (), automatically passes an object as the first parameter

(a function that belongs to a class, which can be called, but must follow the rules of the function, without automatically passing the value.)

Two: Non-binding Method: The method of decorating with Staticmethod ornament

1. Classes and objects can be called without binding to classes or objects, but no automatic values are passed. It's just an ordinary tool.

Note: Separate from bound to object methods, functions directly defined in the class, not decorated by any adorner, are bound to the object's method, not the normal function, the object calls the method will automatically pass the value, and Staticmethod decoration method, no matter who calls, no automatic value to say

1 Staticmethod

Statimethod is not bound to classes or objects, anyone can call, no automatic value effect, Python for our built-in function Staticmethod to define the function in the class as a static method

Import Hashlibimport timeclass MySQL:    def __init__ (self,host,port):        self.id=self.create_id ()        self.host =host        self.port=port    @staticmethod    def create_id (): #就是一个普通工具        m=hashlib.md5 (str (Time.clock ()). Encode (' Utf-8 '))        return m.hexdigest () print (mysql.create_id) #<function mysql.create_id at 0x0000000001e6b9d8> #查看结果为普通函数conn =mysql (' 127.0.0.1 ', 3306) print (conn.create_id) #<function mysql.create_id At 0x00000000026fb9d8> #查看结果为普通函数

2 Classmethod

Classmehtod is used for classes, which are bound to classes, which, when used, will pass the class itself as a parameter to the first parameter of the class method (that is, the object calls the class as the first parameter), and Python has built the function Classmethod to define the function in the class as a class method

host= ' 127.0.0.1 ' port=3306db_path=r ' C:\Users\Administrator\PycharmProjects\test\ object-oriented programming \test1\db '
settings.py Content
Import Settingsimport hashlibimport timeclass MySQL:    def __init__ (self,host,port):        self.host=host        Self.port=port    @classmethod    def from_conf (CLS):        print (CLS)        return CLS (settings. Host,settings. PORT) print (mysql.from_conf) #<bound method mysql.from_conf of <class ' __main__. MySQL ' >>conn=mysql.from_conf () print (Conn.host,conn.port) conn.from_conf () #对象也可以调用, but the first parameter passed by default is still class

Python (21)

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.