Python Basics (17) _ Object-oriented programming (abstract class, inheritance principle, encapsulation, polymorphism, binding method)

Source: Internet
Author: User
Tags define abstract

first, abstract class

  An abstract class is a special class that is unique in that it can only be inherited and cannot be instantiated.

1. Implement abstract classes in Python

Import ABC #利用abc模块实现抽象类Class All_file (METACLASS=ABC. Abcmeta): all_type= ' file '@abc. Abstractmethod #定义抽象方法 without the need for functionalitydef read (self): ' subclass must define read function ' Pass@abc. Abstractmethod #定义抽象方法 without the need for functionalitydef write: ' Subclass must define write function ' pass# class txt (all_file): # pass## T1=txt () #报错, subclass does not define abstract method class TXT (all_file): #子类继承抽象类, but the read and write methods must be defineddef read (self): print (' Read method of text data ') def write (self): print (' Read method of text data ') class Sata (All_file): #子类继承抽象类, but must be Define the Read and write Methods def read (self): print (' Read method of hard drive data ') def write (self): print (' Read method of hard drive data ') Wenbenwenjian=txt () Yingpanwenjian=sata () #这样大家都是被归一化了, the thought of all Documents Wenbenwenjian.read () Yingpanwenjian.write ()

2. Abstract class and interface

The essence of an abstract class is also a class, which refers to the similarity of a set of classes, including data attributes (such as All_type) and function properties (such as read, write), while the interface only emphasizes the similarity of function properties.

Abstract classes are a direct concept between classes and interfaces, with some of the features of classes and interfaces that can be used to implement a normalized design

Second, the implementation of the principle of inheritance (inheritance order)

1. In Python, if a class inherits multiple classes, it looks for two ways: breadth first and depth first

  When a class is a modern class , multiple inheritance cases will be searched in terms of breadth first

  When a class is a classic class , multiple inheritance cases are searched in the depth-first way

If there is an inheritance relationship for the A-h class, the following:

  

#新式类: Class A (object):    def Test (self):        print ("from A")    Passclass B (a):    # def test (self):    #     Print (' from B ')    passclass C (a):    # def test (self):    #     print (' from C ')    passclass D (a):    # def Test (self):    #     print (' from D ')    passclass E (B):    # def test (self):    #     print (' from E ')    passclass F (C):    # def test (self):    #     print (' from F ')    passclass G (D):    # def test (self): c24/>#     print (' from G ')    passclass H (e,f,g):    # def test (self):    #     print (' from H ')    passh= H () # h.test=1# print h.__dict__#新式类的在这中继承结构下, property lookup Relationship # H->e->b->f->c-g-d-a Breadth First # Classic class in this inheritance structure, Lookup relationship for attribute # h-e-b-a-f-c-g-d Depth First

2. Principle of inheritance

How python actually implements inheritance, for each class you define, Python calculates a list of method parsing orders (MRO), which is a simple linear sequential list of all base classes, such as

1>>>F.mro () #等同于F. __mro__2[<class '__main__. F', <class '__main__. D', <class '__main__. B', <class '__main__. E', <class '__main__. C', <class '__main__. A', <class 'Object';]

To implement inheritance, Python finds the base class from left to right on the MRO list until the first class that matches the property is found.
The construction of this MRO list is implemented by a C3 linearization algorithm. We're not going to delve into the math of this algorithm, it's actually merging all of the parent's MRO lists and following three guidelines:

1. Subclasses are checked before the parent class
2. Multiple parent classes are checked according to their order in the list
3. If there are two valid choices for the next class, select the first parent class

3. Calling the parent class method in a subclass

There are two ways of doing this:

1. People.__init__ (self,name,age,sex) # Call the __init__ function of the people class by names

2,super (). __init__ (name,age,sex) # Call the __init__ function of the parent class, actually using the binding method,super only finds once

Class people:    def __init__ (self,name,age,sex):        self.name=name        self.age=age        self.sex=sex    def Foo (self):        print (' From parent ') class Teacher (People):    def __init__ (self,name,age,sex,salary,level):        # people.__init__ (self,name,age,sex) #指名道姓地调用People类的__init__函数        #在python3中        super (). __init__ (Name,age,sex) #调用父类的__init__的功能, the binding method is actually used, super finds only once
       Self.salary=salary self.level=level def foo (self): super (). Foo () print (' from child ') t= Teacher (' Egon ', ' Male ', 3000,10) # print (T.name,t.age,t.sex,t.salary,t.level) T.foo ()

  

Three, Package

1, encapsulation is not a simple meaning of the hidden:

1: The main reason for encapsulating data is: Protecting privacy

2: The main reason for the encapsulation method is: Isolation complexity

2, the package is divided into two levels

1) The first level of encapsulation (nothing to do): Creating classes and objects creates the namespace of both, and we can only use the class name. or obj to access the name inside, which is itself a package; for this level of encapsulation (hidden), the class name. and the instance name. Is the interface that accesses the hidden property

2) The second level of encapsulation: In a class, some attributes and methods are hidden (or defined as private), used only inside the class, inaccessible externally, or left with a small number of interfaces (functions) for external access.     

Implement hidden properties (set to private) in Python with double underlines

Names that begin with all double underscores in a class, such as __x , are automatically formed:_ class name __x form:

Class A:    __n=0 #类的数据属性就应该是共享的, but it is syntactically possible to set the data property of a class to private, such as __n, which is deformed to _a__n# this deformation operation only occurs in the definition phase of    def __init__ (self):        self.__x=10 #变形为self. _a__x    def __foo (self): #变形为_A__foo        print ("from A")    def Bar (self):        Self.__foo () #只有在类内部才可以通过__foo的形式访问到. Outside of the class, you cannot directly use the Deformed property # to access the hidden function in the external way: T=a () T._a__foo ()

Features of this automatic deformation:

1. Defined in the class __x can only be used internally, such as Self.__x, which is referred to as the result of deformation .

2. This deformation is in fact the external deformation , the outside is not accessible by the name __x.

3. The __x defined in the subclass does not overwrite the __x defined by the parent class, because the subclass is formed: The subclass name is __x, and the parent class is formed: The parent class name __x, that is, when the double-glide line begins with a property that inherits to the subclass, the subclass cannot be overwritten.

4. This mechanism also does not really restrict our direct access to properties from the outside, know the class name and property name can be spelled out name: _ Class Name __ property, then you can access, such as A._a__n

3. packages used in combination with property
Class People:def __init__ (self,name,age,sex,height,weight,permission=false): Self.__name=name self.__age =age self.__sex=sex self.__height=height self.__weight=weight self.permission=permission @property #只读 def name (self): return self.__name@name. Setter#可写 def name (self,val): If not isinstance (VAL,STR): Raise TypeError (' name must be string ') Self.__name=va L @name. deleter #可删除 def name: If not self.permission:raise permissionerror (' Insufficient permissions ') del Self.__name@propertydef BMI (self): return self.__weight/(SELF.__HEIGHT**2) def tell_info (self): print ('--------%s Info----------name:%s age:%s sex:%s height:%s weight:%s----------------------- ---"% (self.__name,self.__name,self.__age,self.__sex,self.__height,self.__weight)) egon=people (' Egon ', ' Male ' ', 1.76,72)Egon.tell_info ()Print (Egon.name)egon.name= ' Alex 'Print (egon.name) # egon.permission=true# del egon.nameprint (EGON.BMI)

  

Polymorphism and polymorphism of four states

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

1. Sequence types are available in several forms: string, list, and tuple.

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

1 Import ABC2 classAnimal (metaclass=ABC. Abcmeta): #同一类事物: Animals3 @abc. Abstractmethod4 def talk (self):5 Pass6 7 classpeople (Animal): #动物的形态之一: People8 def talk (self):9Print'Say hello')Ten  One classDog (Animal): #动物的形态之二: Dogs A def talk (self): -Print'say Wangwang') -  the classPig (Animal): #动物的形态之三: Pig - def talk (self): -Print'say Aoao')

2, polymorphism refers to functions with different functions can use the same function name, so you can use a function name to invoke functions of 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.

1>>>def func (animal): #参数animal就是对态性的体现2 ... animal.talk ()3 ... 4>>> people1=people () #产生一个人的对象5>>> pig1=Pig () #产生一个猪的对象6>>> dog1=Dog () #产生一个狗的对象7>>>func (People1)8 Say hello9>>>func (PIG1)Ten say Aoao One>>>func (DOG1) ASay Wangwang

3. The benefits of polymorphism

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

1>>>classCat (Animal): #属于动物的另外一种形态: Cat2 ... def talk (self):3... print ('say Miao')4 ... 5>>>def func (animal): #对于使用者来说, your code doesn't have to change at all6 ... animal.talk ()7 ... 8>>> cat1=Cat () #实例出一只猫9>>>func (CAT1) #甚至连调用方式也无需改变, you can call the cat talk functionTen say Miao One  A " " - 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, called Func (CAT1), in the same way as humans, dogs, and pigs - " "
Iv. 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. classes are tailored to the class . Boud_method (), which automatically passes the class as the first parameter ( actually the object can also be called, but still passes the class as the first parameter )

2. methods bound to an object : There is no way to decorate it with any adorner. Tailor objects to Objects . Boud_method (), automatically passing objects 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 decorate the method, regardless of who call, There's no automatic value.

Binding method: Who is bound to whom is to use

class people:    def __init__ (self,name):        self.name=name    def bar (self):        print ('  --->', self.name)    @classmethod    def func (CLS):        print (CLS F=people ('Egon')# Print (people.func) #绑定给类 # Print (F.bar) #绑定给对象的 # People.func () # F.func () 

2, Staticmethod: Not with the class or object binding, who 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> #查看结果为普通函数

3, Classmethod:classmehtod is for the class, that is, bound to a class, the class will use the class itself as a parameter to the first parameter of the class method (that is, the object to invoke also will be the class as the first parameter passed), Python has built a function Classmethod for us to define the functions in the class as class methods

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 Basics (17) _ Object-oriented programming (abstract class, inheritance principle, encapsulation, polymorphism, binding method)

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.