current position：Home>The second bullet of class in Python
The second bullet of class in Python
2022-01-31 19:57:44 【A program cat】
「 This is my participation 11 The fourth of the yuegengwen challenge 16 God , Check out the activity details ：2021 One last more challenge 」
Methods in class
A method is a special function encapsulated in a class .
class Person: def sing(self): # Method , Writing functions in a class is called defining methods in a class . print(" I am the most handsome ！") # There is a default value none. print(" I am the most handsome ！",none) wuhan = Person() # Define examples , Required for writing . wuhan.sing() # Call the methods in the class . Format ： Instantiate objects . Method () Person.sing(self = ' Something to pass in ') Copy code
Example method Call procedure and self：：：
（1）self： Usually , Name the parameter that will be passed in by default as self, Used to represent the instance object that calls this method itself .
（2） Example method ： Methods are always defined in classes , But it's called “ Example method ”, Because it represents the behavior common to all instances of the class .
Little knowledge points ：：：self It's an example , Who will use it , So who is it .
class Person: def sing(self): print(" The teacher is singing %s"%self.geci) print(id(self)) # You'll find self Of id And the following laoshi Of id It's the same laoshi = Person() # In this case ,laoshi Used self, therefore self Namely laoshi print(id(laoshi)) # Just like the parameters of a function , Just pass an instance of itself first self laoshi.geci = " Warm loneliness " laoshi.sing() Copy code
init Double underline
Initialization method , The function is to instantiate , Automatically call .（ Magic methods ）
“ initialization ” Special methods ：
stay Python There are many fixing methods that start with a double underline and end with a double underline , They will be triggered to execute at a specific time .
__init__ Is one of them , It will be called automatically after instantiation . To complete the initialization of the instance .
When you create an object , Implement some initialization operations for objects , Provide some default values , Only when the instance attribute needs to be defined for the class will __init__ Method .
class Person: def __init__(self.name): self.name = name #self.name Is the instance property ;name Is the method . def sing(self): print(' Wu is the most handsome ') wumou = Person(" Wu ") # Instantiation Automatically call our initialization method , Gave the name Wu to name （ This code means wumou.name = " Wu "（ Define an instance property ) wumou.name amount to self.name," Wu " It's like giving name） Copy code
Magic methods ： Every magic method has its specific function .
Little knowledge points ：
stay python in , The point has been deleted , It will be recycled .
del Delete pointing to , If a variable points to no, it will be recycled .
del That's what's called __init__ Magic methods .
for example ： In the list method ,del List name , When you check this list again, you will report an error , because del Delete the point .
del destructor , Also called destroy initialization method （ Destroy the one above ）, After this file runs, it triggers .（ Magic methods ）
__del__ Is a destructor , When using del When deleting objects , Will call its own destructor . Prompt developers , The object is destroyed , Convenient debugging , Do some necessary cleaning work
Understanding is simple ：（ When the number of instance object references is 0 This magic method will be called when ）
That is, when... Is used in the class del When magic methods , If used del Delete , Then it will call __del__ Magic methods ; If not used del Delete , So at the end of the program , Will automatically reclaim the memory address , Will call __del__ Magic methods .
class Person: pass hansha = Person() print(hansha) # Output is ：hansha The instantiated object points to the object . That is to say ：<__main__.Person object at 0x00000175C3AFC1D0> del hansha print(hansha) # The output will report an error , Because the point was deleted . That is to say ：NameError: name 'hansha' is not defined Copy code
A little upgrade ：
python The execution of a program in , Memory space will be reclaimed , If you recycle it, there will be no point .
class Person: def __del__(self): # Equivalent to rewriting python Of __del__ Method . Use... In the list del When deleting, you call python default __del__ Method . print(' study hard ') hansha = Person() print(11111) print(22222) Output is ： 11111 22222 study hard Copy code
Take a comparative example and take a closer look ：
When the pointer is deleted, it will call __del__ Magic methods .
class Person: def __del__(self): print(' study hard ') hansha = Person() print(11111) del hansha print(22222) Output is ： 11111 study hard 22222 Copy code
Advanced version of summary ：
Object destruction mechanism based on variable counting
When no variable points to an object ,python Will automatically destroy this object , To reclaim memory space .
del keyword , You can delete the point of a variable .
class Person: def __init__(self,name): # Initialization method self.name = name def __del__(self): # destructor （ Destruction method ） print(self.name," Destroyed ") wuhan = person(" unknown ") del wuhan # Output is ： Destroyed Copy code
author[A program cat],Please bring the original link to reprint, thank you.
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
- 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