Chapter 8: Object-Oriented Programming Fundamentals

Chapter 8: Object-Oriented Programming Fundamentals

See previous articles:
Chapter 3: Branch Structure
Chapter 4: Loop Structure
Chapter 5: Constructing Program Logic Chapter
6: Using Functions and Modules
Chapter 7: Strings and Common Data Structures
Or go to the column "python tutorial " View


Resource directory: Code (8)
Article resource download: (1-15 chapters)
Link: https://pan.baidu.com/s/1Mh1knjT4Wwt__7A9eqHmng?pwd=t2j3
Extraction code: t2j3

Programmers living in the present should have heard the term "object-oriented programming", and people often ask if they can explain what "object-oriented programming" is in one sentence. Let's take a look at the more formal term first.

"Compose a set of data structures and methods for processing them into objects, summarize objects with the same behavior into classes, hide internal details through class encapsulation, and realize class specialization through inheritance (specialization) and generalization (generalization), through polymorphism (polymorphism) to achieve dynamic dispatch based on object type."

Does this make it even more unclear? So let's take a look at a more easy-to-understand statement. The following paragraph comes from Zhihu .

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-F3eNhpDP-1679200100642)(./res/oop-zhihu.png)]

Note: The above content comes from the Internet and does not represent the author's own views and opinions. It has nothing to do with the author's own position, and the relevant responsibilities are not borne by the author.

We said before that " a program is a collection of instructions ". The statements we write in the program will become one or more instructions when executed and then executed by the CPU. Of course, in order to simplify the design of the program, we introduced the concept of function, put relatively independent and frequently reused code into the function, and just call the function when you need to use these functions; if the function of a function is too complicated and bloated , we can further divide the function into sub-functions to reduce the complexity of the system. But having said so much, I don't know if you have discovered that the so-called programming is that the programmer controls the computer to complete various tasks according to the working method of the computer. However, the way computers work is different from normal human thinking. If programming, you have to abandon the normal way of thinking of humans to cater to computers, and the fun of programming will be much less. "Everyone should learn programming" such rhetoric I can only talk about it. Of course, these are not the most important. The most important thing is that when we need to develop a complex system, the complexity of the code will make development and maintenance work difficult, so in the late 1960s, the "software crisis " , " Software Engineering " and a series of concepts began to appear in the industry.

Of course, everyone in the programmer circle knows that there is no " silver bullet " to solve the above-mentioned problems in reality. What really makes software developers see hope is the Smalltalk programming language that was born in the 1970s. Object-oriented programming ideas (the prototype of object-oriented programming can be traced back to the earlier Simula language). According to this programming concept, the data in the program and the function of manipulating the data are a logical whole, we call it "object", and the way we solve the problem is to create the required object and send various objects to the object. According to the news, the cooperation of multiple objects can finally allow us to construct complex systems to solve real-world problems.

Explanation: Of course, object-oriented is not the last "silver bullet" to solve all problems in software development, so almost all advanced programming languages ​​today provide support for multiple programming paradigms, and Python is no exception.

classes and objects

Simply put, classes are blueprints and templates for objects, and objects are instances of classes. Although this explanation is a bit like explaining concepts with concepts, we can at least see from this sentence that classes are abstract concepts, while objects are concrete things. In the world of object-oriented programming, everything is an object, and objects have attributes and behaviors. Each object is unique, and the object must belong to a certain class (type). When we extract the static characteristics (attributes) and dynamic characteristics (behavior) of a large number of objects with common characteristics, we can define something called a "class".

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-d8S7CzC2-1679200100645)(./res/object-feature.png)]

define class

In Python, you can use classkeywords to define classes, and then define methods in the classes through previously learned functions, so that the dynamic characteristics of objects can be described. The code is 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)

Explanation: The functions written in the class are usually called (object) methods, and these methods are the messages that the object can receive.

Create and use objects

After we define a class, we can create objects and send messages to objects in the following ways.

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 Visibility Issues

For the above code, programmers with programming experience in C++, Java, C#, etc. may ask, what kind of access rights (also known as visibility) do we have to Studentbind objects nameand properties. ageBecause in many object-oriented programming languages, we usually set the properties of objects as private (private) or protected (protected), which simply means that no outside access is allowed, and the methods of objects are usually public ( public), because the public methods are the messages that the object can accept. In Python, there are only two types of access rights for attributes and methods, that is, public and private. If you want the attribute to be private, you can use two underscores as the beginning of the attribute name. 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 strictly guarantee the privacy of private properties or methods from the syntax. It just changes the names of private properties and methods to hinder their access. In fact, if you know the rules of changing names, you can still access them. They, the following code can verify this. The reason for this setting can be explained by a famous saying, " We are all consenting adults here ". Because the vast majority of programmers believe that openness is better than closure, and programmers are responsible for their own actions.

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 actual development, we do not recommend setting properties as private, because this will make subclasses inaccessible (described later). So most Python programmers will follow a naming convention to let the attribute name start with a single underscore to indicate that the attribute is protected. Code outside this class should be cautious when accessing such attributes. This approach is not a grammatical rule. The attributes and methods starting with a single underscore are still accessible to the outside world, so it is more often a hint or a metaphor. For this point, you can see my "Python - Those Years " The explanations in the article "The pits we have stepped on" .

Object Oriented Pillars

Object orientation has three pillars: encapsulation, inheritance, and polymorphism. The latter two concepts will be explained in detail in the next chapter. Here we first talk about what encapsulation is. My own understanding of encapsulation is "to hide all the implementation details that can be hidden, and only expose (provide) a simple programming interface to the outside world". The method we define in the class actually encapsulates the data and the operation on the data. After we create the object, we only need to send a message to the object (call the method) to execute the code in the method. That is to say, we You only need to know the name of the method and the parameters passed in (the external view of the method), but not the implementation details inside the method (the internal view of the method).

practise

Exercise 1: Define a class that describes a digital clock.

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

Exercise 2: Define a class that describes a point on a plane and provides methods for moving a point and calculating distance to another point.

Reference answer:

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

Note: The illustrations in this chapter come from the book "Object-Oriented Analysis and Design" by Grady Booch and others. This book is a classic book on object-oriented programming. Interested readers can purchase and read this book to learn more Object-oriented knowledge.

Guess you like

Origin blog.csdn.net/xyx2023/article/details/129649163