Python object-oriented programming language based 07- foundation

This article included in the Python series of articles from entry to the master series

1. Understand object-oriented programming

  Live in the moment programmers should have heard "object-oriented programming" is, often someone asked if he could use the next sentence to explain what "object-oriented programming," we take a look at more formal argument.

  "To a set of data structures and methods for processing their composition objects (Object) , the object with the same behavior grouped into classes (class) , by hiding the internal details of a class encapsulated (encapsulation) , through the realization Laid class inheritance (Inheritance) (Specialization) and generalization (generalization) , through the realization of dynamic assignment based on the object type polymorphism (polymorphism) . "

  So is not it better not understand. So we look at a more user-friendly version, see below:

  Before we said " program is a set of instructions ," we write in the program statement is executed and then will turn to one or more instructions executed by the CPU. Of course, in order to simplify the design process, we introduce a function concept, and often the independent reusable code into function, the need to use these features can function simply call; if a function is too complex and cumbersome function , we can continue to function further segmented into sub-functions to reduce the complexity of the system.

  Having said that, however, I do not know if we find that the so-called programming is the way a computer programmer working in accordance with the control computer to complete various tasks. However, thinking how a computer with a normal human is different, if the program would have to abandon normal human way of thinking to cater to the computer, the fun of a lot less, "everyone should learn programming," such rhetoric We can only talk about it. Of course, they are not the most important, the most important thing is when we need to develop a complex system, the complexity of the work will develop and maintain the code becomes difficult, so in the late 1960s, " software crisis " " software engineering a series of concept" and began to appear in the industry.

  Of course, the people in the circle of programmers know that, in reality, it does not solve the above mentioned "these issues silver bullet ", and truly let software developers see the hope of the 1970s of the last century, the birth of Smalltalk programming language introduced Object-oriented programming ideas (object-oriented programming can be traced back to an earlier prototype of Simula language). According to this concept of programming, functional programming data and operational data is a logical whole, which we call "object" , and the way we solve problems is to create objects and object to issue a wide variety of needs news, collaborative work of multiple objects ultimately allows us to construct complex systems to solve real-world problems.

  Description: The course is not object-oriented software development to solve all the problems of the last "silver bullet", so today's high-level programming language provides support for almost all multiple programming paradigms, Python is no exception.

 

2. Classes and Objects

  Simply put, the class is a blueprint and template objects , and objects are instances of classes . Although this explanation was sort of like the concept in the interpretation of the concept, but at least we can see from this statement, the class is an abstract concept, but the object is a specific thing . In object-oriented programming world, everything is an object, the object has attributes and behavior of each object is unique , but the object belongs to a certain category (type) . When we have a lot of common features of the object of the static characteristics (properties) and the dynamic characteristics (behavior) after all extracted, you can define a named "class" thing.

2.1 Definitions class

  You may be used in Python class keyword defined in the class, and then studied by the previously defined class method function, so that the dynamic features of the object can describe the code as follows.

class Student (Object): 

    # __init__ is a special method for initialization when you create an object 
    # This way we can bind the two properties name and age for students to target 
    DEF  __init__ (Self, name, age): 
        Self .name = name 
        self.age = Age 

    DEF study (Self, COURSE_NAME):
         Print ( ' % S S is learning%. ' % (the self.name, COURSE_NAME)) 

    # the PEP. 8 requires the name of the identifier with a plurality lowercase words with an underscore 
    # but some companies prefer to use the programmer and nomenclature hump (hump identification) 
    DEF watch_movie (Self):
         IF self.age <18 is :
             Print ( '% s can only watch "of bears." ' % self.name)
         the else :
             Print ( ' .% s are watching the big island of love movie ' % self.name)

Description: write functions in the class, we usually call a method (the object), the object of these methods is that messages can be received.

 

2.2 Creating and Using Objects

  When we define a good class, you can create objects in the following way and give the object a message.

DEF main ():
     # create student object and specify the names and ages 
    STU1 = Student ( ' Along ' , 66 )
     # to study Object of a message 
    stu1.study ( ' Python series of articles from entry to the master List ' )
     # to send the object watch_av message 
    stu1.watch_movie () 
    STU2 = Student ( ' black ' , 15 ) 
    stu2.study ( ' Mathematics ' ) 
    stu2.watch_movie () 

main ()

 

3. Access the visibility problem

  For the above code, C ++, Java, C # and other programming experience programmers may ask us to Student object bound to name and age have property in the end what kind of access (also called visibility). Because in many object-oriented programming languages, we will usually target property is set to private (private) or protected (protected), simply put, is not allowed to access the outside world, while the method of the object are usually public ( public), because the disclosed method is that objects accept message. In Python, access the properties and methods of only two, that is, public and private , if you want the property is private property in the name to be used two underscore beginning , the following code can verify this.

class Test:

    def __init__(self, foo):
        self.__foo = foo

    def __bar(self):
        print(self.__foo)
        print('__bar')


def main():
    test = Test('hello')
    # AttributeError: 'Test' object has no attribute '__bar'
    # test.__bar()
    # AttributeError: 'Test' object has no attribute '__foo'
    # print(test.__foo)


if __name__ == "__main__":
    main()

   However, Python does not guarantee strict privacy private property or method from the grammar, it just gives private properties and methods of a change of name to hinder access to them, in fact, change the name if you know the rules still have access to they, the following code can verify this. The reason for this setting, can be explained by such a famous saying, that " We are here Wallpaper All Consenting Adults ." Because most programmers think better open than closed, and programmers responsible for their own behavior.

class Test:

    def __init__(self, foo):
        self.__foo = foo

    def __bar(self):
        print(self.__foo)
        print('__bar')


def main():
    test = Test('hello')
    test._Test__bar()
    print(test._Test__foo)


if __name__ == "__main__":
    main()

  In the actual development, we do not recommend the property to private , because it would lead to a subclass can not access (will be mentioned later). So most Python programmers will follow a naming convention is to make the property name with a single leading underscore to represent the property is protected , this code outside of class during a visit to the property that should remain cautious. This practice is not grammatical rules, a single underscore the properties and methods of the outside world is still accessible, so the more often it is a hint or metaphor.

 

4. Object-oriented strut

  Object-oriented three pillars: encapsulation, inheritance, and polymorphism . Two behind the concept is described in detail in the next one, where we first word on what the package. My own understanding of the package is " hidden everything can hide implementation details, exposing only (provide) a simple programming interface to the outside world ." We in fact, the data and operations on the data encapsulated in the method defined in the class up, after we create an object, just to give an object sends a message (call a method) method of the code can be executed, that we only you need to know the name and the incoming method parameters (external view method), without the need to know the internal implementation details of the method (internal view of the method).

 

5. Practice

Exercise 1: define a class description digital clock

Answer:

from time import sleep

class Clock(object):
    """数字时钟"""

    def __init__(self, hour=0, minute=0, second=0):
        """初始化方法

        :param hour: 时
        :param minute: 分
        :param second: 秒
        """
        self._hour = hour
        self._minute = minute
        self._second = second

    def run(self):
        """走字"""
        self._second += 1
        if self._second == 60:
            self._second = 0
            self._minute += 1
            if self._minute == 60:
                self._minute = 0
                self._hour += 1
                if self._hour == 24:
                    self._hour = 0

    def show(self):
        """显示时间"""
        return '%02d:%02d:%02d' % \
               (self._hour, self._minute, self._second)


def main():
    clock = Clock(23, 59, 58)
    while True:
        print(clock.show())
        sleep(1)
        clock.run()


if __name__ == '__main__':
    main()

 

Output:

23:59:58
23:59:59
00:00:00
... ...

 

Exercise 2: define a class method described points in a plane and provide motion and point to point distance computing

Answer:

from Math Import sqrt 

class Point (Object): 

    DEF  the __init__ (Self, X = 0, Y = 0):
         "" " Initialization Method 
        
        : param x: abscissa 
        : param y: vertical coordinate 
        " "" 
        self.x = X 
        Self .y = Y 

    DEF move_to (Self, X, Y):
         "" " moves to the specified location 
        
        : param x: new abscissa 
        " param y: new ordinate 
        "" " 
        self.x = X 
        self.y = Y 

    DEF move_by (Self, dx, dy):
         "" "Moves the specified increments
        
        : param dx: incremental abscissa 
        "param dy: ordinate increment 
        " "" 
        self.x + = DX 
        self.y + = Dy 

    DEF distance_to (Self, OTHER):
         "" " Methods and another point distance 
        
        : param other: another point 
        "" " 
        DX = self.x - other.x 
        Dy = self.y - other.y
         return sqrt (DX ** 2 ** 2 + Dy ) 

    DEF  __str__ (Self):
         return  ' (% S,% S) ' % (STR (self.x), STR (self.y)) 


DEF main ():
    p1 = Point(1, 2)
    p2 = Point(2, 1)
    print(p1)
    print(p2)
    p2.move_by(-1, 2)
    print(p2)
    print(p1.distance_to(p2))

Output:

(1, 2)
(2, 1)
(1, 3)
1.0

  Description: The illustrations in this chapter comes from Grady Booch and other works of "Object-Oriented Analysis and Design" , a book is to explain the object-oriented programming classics, interested readers can buy and read this book to find out more object-oriented knowledge.

 

Guess you like

Origin www.cnblogs.com/along21/p/11886126.html