Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand Python object-oriented programming

2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to understand Python object-oriented programming", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn how to understand Python object-oriented programming.

Object-oriented programming is a very popular programming paradigm (programming paradigm). The so-called programming paradigm is the methodology of programming, that is, programmers' cognition and understanding of the program.

Classes and objects

If you want to summarize object-oriented programming in one sentence, I think the following statement is quite accurate.

Object-oriented programming: the object is composed of a group of data and the methods of dealing with the data, and the objects with the same behavior are classified into classes. By encapsulating the internal details of hidden objects, the class is specialized and generalized through inheritance. Dynamic dispatch based on object type is realized through polymorphism.

This sentence may be difficult for beginners to understand, but let's circle a few key words for you first: object, class, encapsulation, inheritance, polymorphism.

Let's start with the words class and object. In object-oriented programming, class is an abstract concept and object is a concrete concept. We extract the common features of the same class of objects as a class, such as what we often call human beings, which is an abstract concept, and each of us is a concrete and real existence under the abstract concept of human beings. that is, an object. In short, a class is the blueprint and template of an object, and an object is an instance of a class.

In the world of object-oriented programming, everything is an object, objects have properties and behaviors, each object is unique, and the object must belong to a class. The attribute of the object is the static characteristic of the object, and the behavior of the object is the dynamic characteristic of the object. According to the above, if we extract the attributes and behaviors of objects with common characteristics, we can define a class.

Define CLA

In Python, you can use the class keyword plus the class name to define the class, and you can determine the code block of the class by indenting it, just as you would define a function. In the code block of the class, we need to write some functions, we said that the class is an abstract concept, then these functions are the extraction of the common dynamic features of a class of objects. The function written in the class is often called a method, which is the behavior of the object, that is, the message that the object can receive. The first parameter of a method is usually self, which represents the object itself that receives the message.

Class Student:

Def study (self, course_name):

Print (f' students are learning {course_name}.')

Def play (self):

Print (students are playing games.) Create and use objects

After we have defined a class, we can use the constructor syntax to create the object, as shown below.

Stu1 = Student ()

Stu2 = Student ()

Print (stu1) #

Print (stu2) #

Print (hex (id (stu1)), hex (id (stu2) # 0x10ad5ac50 0x10ad5acd0

The so-called constructor syntax is followed by parentheses after the name of the class. The above code creates two student objects, one assigned to the variable stu1 and the other copied to the variable stu2. When we print the stu1 and stu2 variables with the print function, we will see that the address of the object in memory (in hexadecimal form) is output, which is the same as the value we obtained by looking at the object ID with the id function. Now we can tell you that the variable we define actually stores the logical address (location) of an object in memory, and through this logical address, we can find the object in memory. So assignment statements like stu3 = stu2 don't create new objects, they just store the addresses of existing objects with a new variable.

Next, we try to send a message to the object, that is, to call the object's method. In the Student class just now, we defined two methods, study and play. The first parameter of the two methods, self, represents the student object that received the message, and the second parameter of the study method is the name of the course you are learning. In Python, there are two ways to send messages to objects, see the following code.

# through "class. method" invokes the method, the first parameter is the object that receives the message, and the second parameter is the name of the course you are learning

Student.study (stu1, 'Python programming') # students are learning Python programming.

# through the "object. method" calls the method, and the object before the point is the object that receives the message, and only the second parameter is passed in

Stu1.study ('Python programming') # students are learning Python programming.

Student.play (stu2) # students are playing games.

Stu2.play () # students are playing games. Initialization method

You may have noticed that the student object we just created has only behavior and no properties. If we want to define properties for the student object, we can modify the Student class and add a method named _ _ init__ for it. When we call the constructor of the Student class to create an object, we first get the memory space needed to hold the student object in memory, and then initialize the memory by automatically executing the _ _ init__ method, that is, putting the data into the memory space. So we can assign a property to the student object by adding a _ _ init__ method to the Student class, and at the same time assign an initial value to the property, which is why the _ _ init__ method is often referred to as an initialization method.

We modify the Student class above slightly to add name (name) and age (age) attributes to the student object.

Class Student:

"" Student ""

Def _ _ init__ (self, name, age):

"" initialization method ""

Self.name = name

Self.age = age

Def study (self, course_name):

"Learning"

Print (f'{self.name} is learning {course_name}.')

Def play (self):

"" play ""

Print (f'{self.name} is playing a game.)

Modify the code that just created the object and sent messages to the object, and execute it again to see how the execution result of the program has changed.

# because the initialization method has two parameters besides self

# so pass in these two parameters when calling the constructor of the Student class to create an object

Stu1 = Student ('Luo Hao', 40)

Stu2 = Student ('King sledgehammer', 15)

Stu1.study ('Python programming') # Luo Hao is studying Python programming.

Stu2.play () # Wang sledgehammer is playing games. Print object

Above, we use the _ _ init__ method to bind properties to the object and give it an initial value when it is created. In Python, methods that begin and end with two underscores _ (pronounced "dunder") are usually methods with special purpose and meaning, and we generally call them magic methods or magic methods. If we do not want to see the address of the object but our custom information when printing the object, we can do this by placing the _ _ repr__ magic method in the class. The string returned by this method is what will be displayed when the object is printed with the print function. The code is as follows.

Class Student:

"" Student ""

Def _ _ init__ (self, name, age):

"" initialization method ""

Self.name = name

Self.age = age

Def study (self, course_name):

"Learning"

Print (f'{self.name} is learning {course_name}.')

Def play (self):

"" play ""

Print (f'{self.name} is playing a game.)

Def _ repr__ (self):

Return f'{self.name}: {self.age} 'stu1 = Student (Luo Hao, 40)

Print (stu1) # Luo Hao: 40

Students = [stu1, Student ('Wang Xiaohammer', 16), Student ('Wang Da Hammer', 25)]

Print (students) # [Luo Hao: 40, Wang Xiaohammer: 16, Wang Dahe: 25] object-oriented pillar

Object-oriented programming has three pillars, which are the three words we circled when we highlighted them: encapsulation, inheritance and polymorphism. The next two concepts will be explained in detail in the next lesson, so let's talk about what encapsulation is. My own understanding of encapsulation is to hide all the implementation details that can be hidden and only expose simple invocation interfaces to the outside world. The object method we define in the class is actually a kind of encapsulation, which allows us to execute the code in the method only by sending a message to the object after creating the object. that is to say, we only know the name and parameters of the method (the external view of the method) and do not know the internal implementation details of the method (the internal view of the method).

For example, if you want to control a robot to pour me a glass of water, if you don't use object-oriented programming and don't do any encapsulation, then you need to issue a series of instructions to the robot. Such as stand up, turn left, take 5 steps forward, pick up the water cup in front of you, turn backward, walk 10 steps forward, bend over, put down the water cup, press the water button, wait 10 seconds, release the water button, pick up the water cup, turn right, walk forward 5 steps, put down the water cup, etc., in order to complete this simple operation, I find it troublesome to think about it. According to the idea of object-oriented programming, we can encapsulate the operation of pouring water into a method of the robot, and when we need the robot to help us pour water, we only need to send a message of pouring water to the robot object. Isn't that better?

In many scenarios, object-oriented programming is actually a three-step problem. The first step is to define the class, the second step is to create the object, and the third step is to send messages to the object. Of course, sometimes we don't need the first step, because the class we want to use may already exist. As we said before, Python's built-in list, set, and dict are not functions but classes. If we want to create list, collection, and dictionary objects, we don't need to customize classes. Of course, some classes are not provided directly in the Python standard library, but may come from third-party code, and how to install and use third-party code will be discussed later in the course. In some special scenarios, we will use an object called "built-in object". The so-called "built-in object" means that the first and second steps of the above three steps are not needed, because the class already exists and the object has been created. Just send a message to the object directly, which is what we often call "out of the box".

Classic case example 1: define a class to describe a digital clock. Import time# defines a digital clock class

Class Clock (object):

"" Digital clock ""

Def _ _ init__ (self, hour=0, minute=0, second=0):

Initialization method

: param hour: hour

: param minute: points

: param second: seconds

"

Self.hour = hour

Self.min = minute

Self.sec = second

Def run (self):

"Zouzi"

Self.sec + = 1

If self.sec = = 60:

Self.sec = 0

Self.min + = 1

If self.min = = 60:

Self.min = 0

Self.hour + = 1

If self.hour = = 24:

Self.hour = 0

Def show (self):

"" Show time ""

Return f'{self.hour:0 > 2d}: {self.min:0 > 2d}: {self.sec:0 > 2d}'# create clock object

Clock = Clock (23,59,58)

While True:

# send a message to the clock object to read time

Print (clock.show ())

# dormant for 1 second

Time.sleep (1)

# send a message to the clock object to make it disappear

Clock.run () example 2: defines a point on the description plane of a class that requires a method to calculate the distance to another point. Class Point (object):

"" points on the screen ""

Def _ _ init__ (self, x, y, y):

Initialization method

: param x: Abscissa

: param y: ordinate

"

Self.x, self.y = x, y

Def distance_to (self, other):

Calculate the distance from another point

: param other: another point

"

Dx = self.x-other.x

Dy = self.y-other.y

Return (dx * dx + dy * dy) * * 0.5

Def _ str__ (self):

Return f'({self.x}, {self.y})'p1 = Point (3,5)

P2 = Point (6,9)

Print (p1, p2)

Print (p1.distance_to (p2)) at this point, I believe you have a deeper understanding of "how to understand Python object-oriented programming". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report