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
The sidebar is recommended
- Python crawls the map of Gaode and the weather conditions of each city
- leetcode 1275. Find Winner on a Tic Tac Toe Game(python)
- leetcode 2016. Maximum Difference Between Increasing Elements(python)
- Run through Python date and time processing (Part 2)
- Application of urllib package in Python
- Django API Version (II)
- Python utility module playsound
- Database addition, deletion, modification and query of Python Sqlalchemy basic operation
- Tiobe November programming language ranking: Python surpasses C language to become the first! PHP is about to fall out of the top ten?
- Learn how to use opencv and python to realize face recognition!
guess what you like
-
Using OpenCV and python to identify credit card numbers
-
Principle of Python Apriori algorithm (11)
-
Python AI steals your voice in 5 seconds
-
A glance at Python's file processing (Part 1)
-
Python cloud cat
-
Python crawler actual combat, pyecharts module, python data analysis tells you which goods are popular on free fish~
-
Using pandas to implement SQL group_ concat
-
How IOS developers learn Python Programming 8 - set type 3
-
windows10+apache2. 4 + Django deployment
-
Django parser
Random recommended
- leetcode 1560. Most Visited Sector in a Circular Track(python)
- leetcode 1995. Count Special Quadruplets(python)
- How to program based on interfaces using Python
- leetcode 1286. Iterator for Combination(python)
- leetcode 1418. Display Table of Food Orders in a Restaurant (python)
- Python Matplotlib drawing histogram
- Python development foundation summary (VII) database + FTP + character coding + source code security
- Python modular package management and import mechanism
- Django serialization (II)
- Python dataloader error "dataloader worker (PID XXX) is killed by signal" solution
- apache2. 4 + Django + windows 10 Automated Deployment
- leetcode 1222. Queens That Can Attack the King(python)
- leetcode 1387. Sort Integers by The Power Value (python)
- Tiger sniffing 24-hour praise device, a case with a crawler skill, python crawler lesson 7-9
- Python object oriented programming 01: introduction classes and objects
- Baidu Post: high definition Python
- Python Matplotlib drawing contour map
- Python crawler actual combat, requests module, python realizes IMDB movie top data visualization
- Python classic: explain programming and development from simple to deep and step by step
- Python implements URL availability monitoring and instant push
- Python avatar animation, come and generate your own animation avatar
- leetcode 1884. Egg Drop With 2 Eggs and N Floors(python)
- leetcode 1910. Remove All Occurrences of a Substring(python)
- Python and binary
- First acquaintance with Python class
- [Python data collection] scrapy book acquisition and coding analysis
- Python crawler from introduction to mastery (IV) extracting information from web pages
- Python crawler from entry to mastery (III) implementation of simple crawler
- The apscheduler module in Python implements scheduled tasks
- 1379. Find the same node in the cloned binary tree (Java / C + + / Python)
- Python connects redis, singleton and thread pool, and resolves problems encountered
- Python from 0 to 1 (day 11) - Python data application 1
- Python bisect module
- Python + OpenGL realizes real-time interactive writing on blocks with B-spline curves
- Use the properties of Python VTK implicit functions to select and cut data
- Learn these 10000 passages and become a humorous person in the IT workplace. Python crawler lessons 8-9
- leetcode 986. Interval List Intersections(python)
- leetcode 1860. Incremental Memory Leak(python)
- How to teach yourself Python? How long will it take?
- Python Matplotlib drawing pie chart