[Python basic introduction series] day 10: Python classes and objects

First of all, I have assumed that you are a cute new or have read numerous rubbish articles, and then you still don't understand class and object, but at least you know that there are two things like class and object. I think it's necessary to find a vivid example to explain them.

Because you may not have programming experience,

So we can't understand Python's "classes and objects" by analogy from the programming languages we have learned. Let's use the examples in life:

For example, if you are an engineer in a toy factory, you need to make a machine that can make duck shaped toys in batches. Maybe your ideas are as follows:

def makeDuckMoth():
    #You can put other details here 
    print('Duck mouth finished')
def makeDuckEar(): 
    #You can put other details here 
    print('Duck ears finished')
def makeDuckEye(): 
    #You can put other details here 
    print('Duck eyes finished')
def makeDuckHead(): 
    #You can put other details here
     print('Duck head finished')
def makeDuckWing():
     #You can put other details here
     print('Finished making duck wings')
def makeDuckBody():
     #You can put other details here
     print('Duck body finished')
def makeDuckFoot(): 
    #You can put other details here
     print('Duck feet finished')
def makeDuckMerge():
    #You can put other details here 
print('Duck assembled')
makeDuckMoth() #Making duck mouth
makeDuckEar() #Making duck ears
makeDuckEye() #Making duck eyes
makeDuckHead() #Making duck heads
makeDuckWing() #Making duck wings,

##Note that pigs have no wings makeDuckBody() #Making duck body makeDuckFoot() #Making duck feet makeDuckMerge() #Combine all parts of the duck to assemble the final duck

You find that you are so powerful that you have learned the whole duck production process

 

The next day, the boss asked you to make a pig shaped toy. Is your code as follows:? ?


 
def makePigMoth():
     #You can put other details here
     print('Finished making pig mouth')
def makePigEar():
     #You can put other details here
     print('Pig ears finished')
def makePigEye():
     #You can put other details here
     print('Pig eyes finished')
def makePigHead():
     #You can put other details here
     print('Finished making pig head')
def makePigBody():
     #You can put other details here
     print('Pig body finished')
def makePigHand():
     #You can put other details here
     print('Finished making pig's hands')
def makePigFoot():
     #You can put other details here 
     print('4 Pig feet finished')
def makePigMerge(): 
    #You can put other details here
     print('Pig assembled')
makePigMoth() #Making pig mouth
makePigEar() #Making pig ears
makePigEye() #Making pig eyes
makePigHead() #PigHead making
makePigBody() #Making pig body
makePigFoot() #Making 4 pig feet
makePigMerge() #Combine all parts of pig and assemble into final pig

 

In this way, you did finish the work, but did you feel a little tired?

Do you think there are many similarities between pigs and ducks?

If you've learned how to use a class, it's very easy. Here's how to use a class

  

Wait a minute. Let me talk about it first

 

  1. What are the advantages of classes and objects in actual programming and why they should be used

  2. And I'll explain to you how to understand them

 

The main benefits of class are

  • Easy to reuse (if you write with functions, you need to copy the whole code, increase the code amount and increase the error rate)

  • Convenient extension (function write segment code, if you want to upgrade and expand, it is very complex and error prone, and it is convenient and clear to extend with class)

  • Easy to maintain (because classes map abstract things to common things we can touch, easy to understand, easy to maintain)

 

 

Take a few examples to understand:

Class is like the drawing of gene making. We humans, the children we have, are also two hands, two feet and one mouth. Unless we mutate, we will not have one more foot. The reason for this orderly development is that we have genes in our bodies, which control our reproduction

Now let's create a generic gene table for duck and pig production in the above example, and use them to similar production processes

Establish gene table

class Animal(object):
 ''' Basic classes of pigs and ducks (gene map table) '''
     def __init__(self, name):
     # When instantiating, pass in the name of the thing to be made, such as pig and duck 
         self.name = name def makeMoth(self):
     #You can put other details here
         print(self.name+'The mouth of')
     #Here, self.name is to get the name we passed in
    def makeEar(self):#You can put other details here
         print(self.name+'The ears of')
    def makeEye(self): #You can put other details here 
         print(self.name+''s eyes are finished')
    def makeHead(self): #You can put other details here
         print(self.name+'Finished making the head of')
    def makeBody(self): #You can put other details here 
         print(self.name+'The body of')
    def makeFoot(self): #You can put other details here
         print(self.name+'The feet are finished')
    def makeMerge(self): #You can put other details here
         print(self.name+'Merge completed')
    def makeAll(self): # A dragon. Run the whole assembly line directly
        self.makeMoth()
        self.makeEar()             
        self.makeEye()
        self.makeHead() 
        self.makeBody() 
        self.makeFoot()    
        self.makeMerge()

 

As you can see, in the above drawing, we didn't put makeWing(), which is because pigs can't fly. We only put the same thing that pigs and ducks share. Next, we use this class to inherit it to Pig


The code is as follows

class Pig(Animal):
 # The word "Animal" in parentheses means that Pig inherits all the features of Animal, just like you inherit your father's genes
    def makeMoth(self): #Here is the detailed production process of pig mouth, such as long mouth, with two holes 
        print(self.name+'The mouth of')
    def makeEar(self): #Big ears
        print(self.name+'The ears of')
    def makeEye(self): #Small eyes
        print(self.name+''s eyes are finished')
    def makeHead(self): #Big head 
        print(self.name+'Finished making the head of')
    def makeBody(self): #slightly 
        print(self.name+'The body of')
    def makeFoot(self): #slightly 
        print(self.name+'The feet are finished')
    def makeMerge(self): #slightly 
        print(self.name+'Merge completed')

 

In class Pig, such as the makeMoth function method, only the detailed code for making pig mouth is added. Do not put the code for making pig head here

You can see that there are no such two pieces of code in class Pig, because,

If you inherit other objects, such as Animal, and don't modify some method properties at all, you can not write them out (in fact, they still exist in Pig)

def __init__(self, name): 
    self.name = name
def makeAll(self): # A dragon. Run the whole assembly line directly 
    self.makeMoth() 
    self.makeEar()
    self.makeEye()
    self.makeHead()
    self.makeBody()    
    self.makeFoot() 
    self.makeMerge()

 

 

Writing it out means that you want to override the behavior in the previous code block, such as:

We wrote makeMoth, makeEar

It means that we need to change the details of making in makeMoth to what we want,

The mouth of a pig and a duck are different. The details of their making must be different, right?

 

Finally, we use the following code to let the machine start to build pigs



pig1 = Pig('pig') #Instantiation, equivalent to pregnancy
pig1.makeAll() # Starting to build pigs is equivalent to forming a whole in the womb

 

Now start to make the drawings of ducks, inherit the Animal, and cover some codes

class Duck(Animal): #
     def makeMoth(self): 
    #Here is the detailed duck mouth production process, such as long mouth, hard mouth
         print(self.name+'The mouth of')
    def makeEar(self): #The ears are small. 
        print(self.name+'The ears of')
    def makeEye(self): #Small eyes 
        print(self.name+''s eyes are finished')
    def makeHead(self): #The head is small. 
        print(self.name+'Finished making the head of')
    def makeBody(self): #slightly 
        print(self.name+'The body of')
    def makeFoot(self): #slightly 
        print(self.name+'The feet are finished')
    def makeMerge(self): #slightly 
        print(self.name+'Merge completed')
    def makeWing(self): #Increase the manufacturing process of wings #slightly 
        print(self.name+'Finished making the wings of')
    def makeAll(self): #Because we added wings, we need to override this function 
        self.makeMoth() self.makeEar()         
        self.makeEye() 
        self.makeHead() 
        self.makeBody() 
        self.makeFoot() 
        self.makeWing() #Insert wings production process 
        self.makeMerge()

Then instantiate it with the following code and start to be a duck

duck1 = Duck('Duck')duck1.makeAll()

 

 

In the future, if we want dogs, cows and penguins, we can inherit them from animal. Animal provides us with a framework. We only need to expand and extend this framework to make anything conveniently. This is the charm of this kind

 

 

What if you want to do something else?

We can build a common base class, which is similar to the human ancestor, first microorganism, then monkey


 

 

class Weishengwu(object): '' suppose that the ancestors at the beginning would only eat '' 'def ﹣ init ﹣ (self, Name: self. Name = name def eat(self): print('eat ');' begin to evolve into fish class Fish(Weishengwu): '' learn to move on the basis that the ancestors can only eat '' '' def move(self): print('move ');' begin to evolve into monkey class Houzi(Fish): '' in fish "Def init (self, name, love): Chen used to have only a name, but now he has a hobby. Maybe he eats peaches or swings. self.name = name self.love = love def eat(self): ා overwrite, because the way of eating may be different from that of fish. print('teeth eat ') def move(self): ා overwrite, not in water, but on land. print('foot move') Def Pashu(self): print('tree climbing '). You can continue to evolve and add any work to it

 

summary

I hope this vivid and vivid example can help you understand the definition and use of Python classes and objects. Finally, I will give you a vivid metaphor, hoping you can understand it.

class: equivalent to blueprint

object: a house (already built)

 

Reference resources:

https://www.runoob.com/python3/python3-namespace-scope.html

https://www.zhihu.com/search?type=content&q=python%E4%B8%8E%E5%AF%B9%E8%B1%A1

375 original articles published, 180 praised, 110000 visitors+
Private letter follow

Tags: Programming Python network

Posted on Wed, 11 Mar 2020 08:43:01 -0400 by vahidf