Python core technology and real - nine | Object-Oriented

  Find out in a variety of data types, the assignment judge, after circulation if it is from C ++, Java language start with, there will be a pit to lead: OOP (object oriented programming): There are public and private protection, multiple inheritance, polymorphism derived , pure functions, abstract classes, and so on and so a bunch of friend functions proper nouns waiting How about you! so far so good! Python is a relatively little friendly language, he encouraged an interactive command lightweight programming at its inception. In theory, Python command language is Turing complete, that is imperative languages, in theory, can be left to any and all things in any other language can do, even further, to only rely on the MOV instruction assembly language, it is Turing complete programming can be achieved.

  So why do not we do it? In fact, "ancient times," the programmer is doing so, as the program can gradually improve the functionality of complex, constantly iterative requirements, a lot of old code to modify it very troublesome, simply can not iterative and maintenance, even only reconstruction. This is the reason why the old code called "feces Mountain".

  The traditional imperative languages there are numerous repetitive code, although the birth of a function of reducing a lot of repetitive code. But with the development of computers, and only function it is not enough, take a more abstract concept into a computer in order to ease (note the ease rather than solving), so that OOP is made.

A. Basic concepts

  Fundamental concepts in object-oriented Python articles object-oriented programming and Python object-oriented advanced use had concluded, there is not more to say, in short, is four points, although the summary of interactive very strict, but also can intuitively understand a bit:

    1. class : a collection of people who share a similarity of things, corresponding in Python is a class;

    2. Object : a set of errors, Python class should be generated in on a particular Object;

    3. properties : a static features of the object;

    4. function : the ability of a dynamic object.

Second, several unconventional: class, static functions, etc.

  There are several functions to consolidate what we then:

class peaple (): 
    Nationality = ' China '        # constants / variables class 
    DEF  the __init__ (Self, name, Sex, Age, the salary = 1000):   # Constructor 
        the self.name = name 
        self.sex = Sex 
        self.age = Age 
        Self . __salary = salary   # private property 

    @classmethod                 # class methods, instance property can not be called, can only be called class variables 
    DEF Fun (self):
         Print (self.NATIONALITY) 

    @staticmethod                # static method does not pass the self to the function declaration 
    def fun2(test):
        print(test)

p1 = Peaple('Jack','male',22)
p1.fun()

For this example, it lists a few commonly used methods and properties (a matter of habit, sometimes called the method, also sometimes called function):

1. class variables / constants: For example, this class of object has properties in the abstract class when we can put him out in the example of the time you will not need a special assignment. General class variables are named in capital letters.

2. Class Methods: decorator for declaring the methods class method in the function attributes defined in the constructor can not be called, can only be called in on a class attribute. There is another class attribute usage, it returns a:

    @classmethod
    def new_person(cls,name,sex,age):
        return cls(name=name,sex=sex,age=age)
p1 = Peaple('Jack','male',22)
p2 = p1.new_person('Mary','female',25)

We define a class method, then you can create a new instance by calling the class instance method (not think there is any practical)

3. static methods: static methods and classes have no relevance, just in time to call to add classes. The most straightforward example is similar to the os module, after importing os in fact, the various methods and os This class is no relationship, but when called or to add os

import os
os.open()
os.close()

4. Private property is the only class methods can be invoked, but in the instance can not be called. (Similarly, in the definition of the method when adding "__" Note that two underscore constitutes a private methods, but also can only be used in the construction class, can not be used in the examples).

III. Inherited

  Inheritance is object-oriented in a very important point, that the white subclasses have attributes and functions Ferre. In the next chapter with an example application which we will focus on the way, where he said that:

  1. subclass instantiation will not call the parent class's constructor must be dominant constructor call parent class, (super () .__ init __ ()).

  2. Next, in the method of class definitions of certain time

class A():
    def __init__(self):
        pass

    def fun(self):
        raise Exception('fun is not defined')

  When the parent class's definition of fun, function definitions out this way, in the subclass must reconstruct it, otherwise it will raise error interrupt execution of the program, such an approach is called a function of rewrite can make the subclass must re-write it again function to cover off the original function.

  3. There is also a class is an abstract class, its existence is a parent class exists, once the object of the error will be (like PyQt5 in a variety of base class),

from abc import ABCMeta,abstractclassmethod
class A(metaclass=ABCMeta):

    def __init__(self):
        pass

    @abstractclassmethod
    def fun(self):
        raise Exception('fun is not defined')

  Where A is an abstract class. Abstract class can be a common method for all subclasses into them, but class A is not directly instantiated.

  This is a software function in a very important concept: the definition of the interface. Large projects often need to develop a lot of people, after the idea put forward the development team and product groups will first convene product design, PM write product requirements documents, and iterative; TL (project manager) to write development documents, the document defines the different development and generally function interface module, how to write and inheritance] test unit testing, the gradation test line, so some of the logs, and monitoring the development process between each module. An abstract class is such a presence, he is a top-down design style, only a small amount of code describes clears things to do, good interface definition, then you can give different developers to develop and docking.

  4. Note that the order of succession: demo before that post, too, is summarized in the sentence: In Python2 classical class is to be inherited in a depth-first, breadth-first new class is the successor strategy; Python3 in the Classic and the new classes are inherited in accordance with the breadth-first strategy.

Guess you like

Origin www.cnblogs.com/yinsedeyinse/p/11234904.html