Python100Days study notes --- Day8 the basis of object-oriented programming

Object-oriented programming basics
living 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 a more formal statement .

"To a set of data structures and methods for processing thereof subject (object), the object with the same behavior grouped into classes (class), hide the internal details by class encapsulating (encapsulation), achieve specialization class by inheritance (Inheritance) (Specialization) and generalization (generalization), based on the dynamic object type by assigning polymorphism (polymorphism). "

So is not it better not understand. So we look at a more user-friendly to say, the following piece of content from almost know.

Here Insert Picture Description

Description : The above content from the network, does not represent the views and opinions of the author, and the author himself Lichangwuguan, responsible not help authors assume.

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 introduced the concept of the function, the independent and often reused 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, the "software crisis" , a series of concept "software engineering" 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 "silver bullet" to these questions, the real software developers that want to see the birth of the 70s of last century 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 : Of course not object-oriented software development is 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.

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, and the object must belong to a certain category (type). When we put the static characteristic (property) has a lot of common features of objects and dynamic characteristics (behavior) are extracted, you can define a named "class" thing.

Here Insert Picture Description

Defined classes
may define class class keyword in Python, 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__是一个特殊方法用于在创建对象时进行初始化操作
    # 通过这个方法我们可以为学生对象绑定name和age两个属性
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def study(self, course_name):
        print('%s正在学习%s.' % (self.name, course_name))

    # PEP 8要求标识符的名字用全小写多个单词用下划线连接
    # 但是部分程序员和公司更倾向于使用驼峰命名法(驼峰标识)
    def watch_movie(self):
        if self.age < 18:
            print('%s只能观看《熊出没》.' % self.name)
        else:
            print('%s正在观看岛国爱情大电影.' % 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.

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

def main():
    # 创建学生对象并指定姓名和年龄
    stu1 = Student('骆昊', 38)
    # 给对象发study消息
    stu1.study('Python程序设计')
    # 给对象发watch_av消息
    stu1.watch_movie()
    stu2 = Student('王大锤', 15)
    stu2.study('思想品德')
    stu2.watch_movie()


if __name__ == '__main__':
    main()

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 as two underscores 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 all consenting adults here". 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 allow a single attribute names begin with an 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 metaphor or implied, on this point I can look at the "Python - those years we stepped on those pits "article to explain.

Object-oriented strut
object-oriented three pillars: encapsulation, inheritance, and polymorphism. The latter two concepts in the next chapter a detailed explanation, here let's talk about what is the package. My own understanding of the package is "all hidden 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).

Exercise 1: define a class describes digital clock.

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()

Describes a class method defined point in a plane and provide mobile computing and point to point distance: 2 exercises.

from math import sqrt


class Point(object):

    def __init__(self, x=0, y=0):
        """初始化方法
        
        :param x: 横坐标
        :param y: 纵坐标
        """
        self.x = x
        self.y = y

    def move_to(self, x, y):
        """移动到指定位置
        
        :param x: 新的横坐标
        "param y: 新的纵坐标
        """
        self.x = x
        self.y = y

    def move_by(self, dx, dy):
        """移动指定的增量
        
        :param dx: 横坐标的增量
        "param dy: 纵坐标的增量
        """
        self.x += dx
        self.y += dy

    def distance_to(self, other):
        """计算与另一个点的距离
        
        :param other: 另一个点
        """
        dx = self.x - other.x
        dy = self.y - other.y
        return sqrt(dx ** 2 + dy ** 2)

    def __str__(self):
        return '(%s, %s)' % (str(self.x), str(self.y))


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


if __name__ == '__main__':
    main()
Published 124 original articles · won praise 141 · views 160 000 +

Guess you like

Origin blog.csdn.net/weixin_36838630/article/details/105206478
Recommended