current position:Home>Daily python, Chapter 18, class

Daily python, Chapter 18, class

2022-01-31 20:46:06 Qing'an slag

「 This is my participation 11 The fourth of the yuegengwen challenge 18 God , Check out the activity details :2021 One last more challenge

Preface

         This is Qing'an . After learning the function , Don't learn , That would be a waste of effort , Let's learn how to create and use classes this time , Analysis of collocation examples , So you can understand at a glance !!!

1、 Create a class

1.1、 Know the class

         Let's first get to know , Why use classes , What classes can be used for !

         Class can be understood as a toolbox , You can put all kinds of tools in it , The tool here is what we call the function method , What kind of tools did you put in , You can use it for what , Put in a hammer , You can use it to drive nails , You can smash things , You can do something else , This is what we call a calling class or a method in a calling class .

         First, we create a student name class student_name: I defined a name and an age attribute , It also defines a functional method of running and sleeping .

#  Create a file called student_name Class 
class student_name:
    #  Using special methods __init__(), Initialization property 
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def run(self):
        print(f"{self.name} Run up !")

    def sleep(self):
        print(f"{self.age} Year old {self.name} hit the hay ")
 Copy code 

         analysis : It is worth noting that , We see a new approach here , other run as well as sleep If you don't understand function methods, you can see my article : Function method ,init() Method , Two underscores before and after , Pay attention ! This method is a special method , Also in order not to conflict with other function names .

         init() Method : Here we define three formal parameters ,self It is also indispensable , It is a formal parameter , It initializes properties , In order to facilitate the subsequent value transfer of arguments . In class ,python When calling a method to create an instance and pass values , Will be automatically passed into the argument self in , It is a reference to the instance itself , We pass arguments to student_name class ,self The value will be automatically assigned to the property , To achieve the effect we want .

2、 Create an instance based on the class

         Take the above example , We create a student_name, Let's use classes to create instances

2.1、 Access properties

class Student_name:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def run(self):
        print(f"{self.name} Run up !")

    def sleep(self):
        print(f"{self.age} Year old {self.name} hit the hay ")
names = Student_name(' Zhang San ','12')
#  Start calling properties 
names.name
names.age
print(f" The student's name is {names.name}, He has {names.age} Year old ")
 Copy code 

         In fact, it seems a little redundant here , We are print In fact, we have called the attribute value , So the preceding names.name as well as names.age Small partners can not join in , Here is just a demonstration for you .

2.2、 Calling method

#  Create a file called student_name Class 
class student_name:
    #  Using special methods __init__()
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def run(self):
        print(f"{self.name} Run up !")

    def sleep(self):
        print(f"{self.age} Year old {self.name} hit the hay ")

names = student_name(' Zhang San ','12')
names.run()
names.sleep()
 Copy code 

         This is actually the same as the calling function method we learned before , It's just Written in class , First pass the value to the class , Then it is passed from the class to the function method .

2.3、 Create multiple instances

class Student_name:
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def run(self):
        print(f"{self.name} Run up !")

    def sleep(self):
        print(f"{self.age} Year old {self.name} hit the hay ")

names = Student_name(' Zhang San ','12')
names_1 = Student_name(' Li Si ','13')
names.run()
names.sleep()
names_1.run()
names_1.sleep()
 Copy code 

         To create multiple instances, we need to call multiple methods to achieve the effect

3、 Use classes and instances

         Before using classes and instances, we need to create a class

class Friend_name:
    def __init__(self,name,age,height):
        self.name = name
        self.age = age
        self.height = height
    #  Create a method , Used to summarize all the information of friends 
    def total(self):
        total_message = f"{self.name} This year, {self.age} year , height {self.height}!"
        return total_message

names = Friend_name(' Zhang San ','12',175)
print(names.total())
 Copy code 

         there __init__() Method heel 1.1 The example is the same , Function method total(self) It's our own new definition , In the function, we define another variable , Receive the information we need , And return the variable value . In the end, we call the arguments and variables in the printed value tota Method and output .

3.1、 Specify a default value for the property

         Sometimes we can not define formal parameters , Directly in __init__() Method to specify the default value directly .

         We have defined a new weight attribute :

class Friend_name:
    def __init__(self,name,age,height):
        #  Initialization property 
        self.name = name
        self.age = age
        self.height = height
        #  Define a default value 
        self.weight = 140

    def total(self):
        total_message = f"{self.name} This year, {self.age} year , height {self.height}!"
        return total_message

names = Friend_name(' Zhang San ','12',175)
print(names.total())
print(f" Zhang San weighs :{names.weight} Jin ")
 Copy code 

         After defining the new attribute , We give a default value , This can be called directly , Is that we are 2.1 The call attribute values mentioned in this chapter .

3.2、 Modify attribute values

        3.1 In, we define a default attribute value , Then I can modify it !

class Friend_name:
    def __init__(self,name,age,height):
        self.name = name
        self.age = age
        self.height = height
        self.weight = 140

    def total(self):
        total_message = f"{self.name} This year, {self.age} year , height {self.height}!"
        return total_message
    # Define a new parameter 
    def update_total(self,update_weight):
        self.weight = update_weight
        print(f"{self.name} The weight is {self.weight}")

names = Friend_name(' Zhang San ','12',175)
names.update_total(180)
 Copy code 

         After we define a new parameter , Use self Parameter so that the changed value can be passed in , At the end we call update_total() Function and give it the value you want to modify , And then python The value we give will be passed through the formal parameter self The incoming to weight in , And print a message , It proves that the modification was successful .

3.3、 Increment the attribute value

         Since you can define default values , You can also modify the default value , Of course, you can increment the default value . And it only needs a little change !

class Friend_name:
    def __init__(self,name,age,height):
        self.name = name
        self.age = age
        self.height = height
        self.weight = 140

    def total(self):
        total_message = f"{self.name} This year, {self.age} year , height {self.height}!"
        return total_message
    # Define a new parameter 
    def update_total(self,update_weight):
        #  Let's just change this to operator plus 
        self.weight += update_weight
        print(f"{self.name} The weight is {self.weight}")

names = Friend_name(' Zhang San ','12',175)
names.update_total(10)
 Copy code 

         We will weight Add the newly defined formal parameters , Finally, we call the newly defined formal parameter , adopt self The formal parameter is passed in the value we want to increase .

copyright notice
author[Qing'an slag],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201312046048284.html

Random recommended