How to understand python classes in the simplest and most popular way?

Many beginners start to get confused when they learn “classes”. What exactly is a “class” and what is it used for? Then I searched wildly on Baidu and found a lot. After looking at the answers, many of them were talking about object-oriented, and they also talked about a bunch of weird concepts, which made them even more confused. .

Therefore, this article of mine is to take everyone to understand what a class is, what a class can do, and how to use it in the simplest, most popular, and violent way.

First of all, we need to understand that since the author of python designed the “class”, there must be such a need when programming. So when do we need to use classes? Of course, there are many, many places where classes can be used. But if you don’t have much coding experience, I will tell you the answer directly: If multiple functions need to use the same set of data repeatedly, it will be very convenient to use classes to handle it.

Let me give you an example that everyone has been exposed to in middle school: Solving triangles.

I need to make a module to achieve the following functions: input the three side lengths a, b, c of a triangle, then calculate and return the angles of the three corners of the triangle, as well as the area and perimeter of the triangle.

You will say, this is very simple, we usually just do this, if the side lengths of the input triangle are 6, 7, 8:

def ...: # Define the five functions with reference to the formula, so I won't write them in detail
    ...
def...:
    ...

# Then call the defined function and pass in the side length data
angleA(6,7,8) # calculate angle A
->0.8127555613686607 # Note that the return value is in radians

angleB(6,7,8) # calculate angle B
->1.0107210205683146

angleC(6,7,8) # calculate angle C
->1.318116071652818

square(6,7,8) # Calculate the area
->20.33316256758894

circle(6,7,7) # Calculate the circumference, uh, it seems that there is a wrong number
->20 # The calculation result is of course wrong

Isn’t this done? Define the five functions needed for calculation in turn, and then adjust them. But if you take a closer look, what’s wrong with writing like this? I believe everyone has discovered that This is the same triangle. Every time you calculate the angle, area, and perimeter, you must pass in the lengths of the three sides. On the one hand, this is very troublesome, on the other hand , if one accidentally writes a mistake, then of course the result is wrong.

We can know from the congruent conditions of triangles that if the three sides of a triangle are determined, then its three angles, area, and perimeter are also determined. So for the same triangle, it is best to only need to transfer data once.

Isn’t this simple, just write them all in one function:

def calculate(a,b,c):
    angleA = ...
    angleB = ...
    angleC = ...
    square = ...
    circle=...
    return {<!-- -->'angleA':angleA, 'angleB':angleB, 'angleC':angleC, 'area':square, 'perimeter':circle}

result=calculate(6,7,8)

result['corner A']
->0.8127555613686607

result['area']
->20.33316256758894

Well, this is not done again, it seems that there is no problem. Of course there is no problem, but if you think about it again, If I only need to calculate “angle A” and “area”, using the above method, only these two results will be returned, but in fact, When that function is executed, it actually evaluates all five values. A small number is fine, but if the number increases, the efficiency will definitely be greatly affected.

What to do about this? If you are smart, you may have thought of adding a fourth parameter d to the function to mark which one needs to be calculated, and then insert an if statement in the function to judge…

Well, I don’t want to write the code anymore. The logic that was so clear has to be ruined like this. .

This needs to be easy to use, high in efficiency, and clear in logic. How can this be done? We thought about it and thought that the function should be written separately. But let’s think about it, it’s better to have a “big thing” called “triangle generator” to include these functions. When used, the parameters are directly passed to the triangle generator, and then the triangle generator will generate specific triangles according to the incoming side lengths. In addition to the input side length data, the generated triangles can also calculate their own three. Angle, Area, Perimeter. That is, we hope to achieve the following effects:

# Define a "big thing", the name is triangle
...
...
# Do some magic, then

tr1=triangle(6,7,8) # Pass the three side lengths to this big thing, and then generate a triangle and assign it to tr1

In this line of code, we pass the side length value to the “triangle generator” triangle(), generate a triangle, and then assign it to the variable tr1. At this time, tr1 represents a specific triangle with side lengths of 6, 7, and 8.

Then, we can easily check the lengths of the three sides of the triangle (that is, the data just passed in):

tr1.a
->6

tr1.b
->7

tr1.c
->8

Calculate and view the angles of three corners:

tr1. angleA()
->0.8127555613686607

tr1. angleB()
->1.0107210205683146

tr1. angleC()
->1.318116071652818

Calculate and view its area and perimeter:

tr1. square()
->20.33316256758894

tr1. circle()
->21

Here comes another triangle with side lengths 8, 9, 10:

tr2=triangle(8,9,10) # generate another triangle

Compute the difference in area of these two triangles:

tr2.square()-tr1.square() # tr2 is a newly generated triangle, the original tr1 is still there and has not been deleted
->13.863876777945055

It’s a bold idea, isn’t it? But how should it be achieved? This is where classes are used.

But everyone is thinking about it, is this kind of thinking really smart? In python, everything is an object. When we operate built-in objects such as strings, lists, dictionaries, and file IO, the methods we use look exactly the same. . It’s just that the “triangle” is our own creation. Speaking of this, you may have understood that the class actually provides the ability to customize objects.

Well, without further ado, let’s take a look at the “magical operation” above.

import math # Calculate the inverse trigonometric function to be used
 
class triangle: #Definition class: triangle generator
    def __init__(self,a,b,c): # Member function, declares parameters that need to interact with the outside world (class attributes)
        self.a=a # look first
        self.b=b # What are these things for? I will talk about them later
        self.c=c

    def angleA(self): # calculation function (method of class)
        agA=math.acos((self.b**2 + self.c**2-self.a**2)/(2*self.b*self.c))
        return agA

    def angleB(self): # Go back to the textbook if you don't understand the formula
        agB=math.acos((self.c**2 + self.a**2-self.b**2)/(2*self.a*self.c))
        return agB

    def angleC(self):
        agC=math.acos((self.a**2 + self.b**2-self.c**2)/(2*self.a*self.b))
        return agC

    def square(self):
        p=(self.a + self.b + self.c)/2
        s=math. sqrt(p*(p-self.a)*(p-self.b)*(p-self.c))
        returns

    def circle(self):
        cz=self.a + self.b + self.c
        return cz

In fact, it is also simple, that is, first declare the included parameters, and then write the included functions. The specific writing rules are introduced in many documents, so I won’t go into details.

It is also simple to use. Since the class is the rule of self-leveling objects, we first pass in the data and generate specific objects according to the rules (called instantiation):

tr1=triangle(6,7,8)

Like this, according to the generation rules of the triangle, the length of the three sides passed in, the specific triangle generated, and then those side lengths, angles, and areas will be meaningful.

print(tr1.a)
print(tr1.b)
print(tr1.c)
print(tr1. angleA())
print(tr1. angleB())
print(tr1. angleC())
print(tr1. square())
print(tr1. circle())

->
6
7
8
0.8127555613686607
1.0107210205683146
1.318116071652818
20.33316256758894
twenty one

To sum up, all objects, whether built in python, imported third-party packages, or defined and instantiated by our own class, observe and summarize, we can find that they are composed of two parts, one part is like Data such as a, b, and c, they determine what this object is, and the other part is functions like angleA(), angleB(), angleC(), which are used to express what to do with these data. In object-oriented programming, the data of an object are called the properties of the object, and the functions owned by an object are called the methods of the object. You may often hear these two terms, even in other programming languages, object-oriented as a kind of thinking, are interlinked.

Then you may have a few questions:

What does the first function def __init()__ do?

As the name suggests, init means initialization. The init function, that is, the initialization function, means that when a class is instantiated, the function runs automatically. If we pass parameters to the class when instantiating, the parameters are also submitted to this function. to deal with. Therefore, you can write any function in the init function that you want to be automatically executed when it is instantiated, such as print(‘instantiation completed’) or something.

But most of the time, what do we want to do when we instantiate? Of course, it is to pass the data to the attributes of the class, so in most cases, the init function acts as a constructor, and we can write here who to assign the passed data to, or what kind of process Who will be assigned after preprocessing.

Take that triangle as an example. We hope that when generating a triangle (instantiation), we will pass in three side lengths to the triangle generator (class), instead of tr1.a=6, tr1.b after the instantiation is complete. =7 such assignments one by one. So we directly stated the parameter passing rules in the init function.

In addition, after the instantiation of the incoming parameters, in addition to viewing, it can also be modified again:

tr1.a
->6

tr1.a=7
tr1.a
->7

What is that self, why write self.a?

When we use the properties of the object, the writing method is “object name. property name”, just like tr1.a above. When defining a class, in order to maintain consistency, this way of writing should also be used. However, since the class has not been instantiated when it is defined, it is not clear what the object name is, so you can write any one (but it must be consistent), and generally write self.

After reading this article, you know what a class is, and then search for the information you want, and you can understand it.

About Python technology reserves

Learning Python well is good whether it is employment or sideline business to make money, but to learn Python, you still need to have a study plan. Finally, everyone will share a full set of Python learning materials to help those who want to learn Python!

For beginners with 0 basics:

If you are a zero-based novice, you can consider getting started with Python quickly.

On the one hand, the learning time is relatively short, and the learning content is more comprehensive and concentrated.
On the other hand, you can find a learning plan that suits you

Including: Python activation code + installation package, Python web development, Python crawler, Python data analysis, artificial intelligence, machine learning and other tutorials. Take you to learn Python systematically from zero foundation!

Introduction to zero-based Python learning resources

Python learning route summary

The technical points in all directions of Python are sorted out to form a summary of knowledge points in various fields. Its usefulness lies in that you can find corresponding learning resources according to the above knowledge points to ensure that you can learn more comprehensively. (Get the full set of tutorials at the end of the article)

Python essential development tools

Reminder: The space is limited, the folder has been packed, and the way to obtain it is at the end of the article

Python learning video 600 collection

Watching the zero-based learning video is the fastest and most effective way to learn. Following the teacher’s ideas in the video, it is still very easy to get started from the basics to the in-depth.

100 Python exercises

Check the learning results.

Interview questions

This full version of the full set of Python learning materials has been uploaded to CSDN. If you need it, you can scan the QR code of CSDN official certification below on WeChat to get it for free [guaranteed 100% free]