Article Directory
magic method
There is a method in Python called a magic method. The methods provided in Python classes that start with two underscores and end with two underscores are magic methods. Magic methods will be activated and executed automatically when appropriate.
Two characteristics of the magic method:
- Two underscores on each side;
- The "spell" name has been officially defined by Python, we can't write it randomly.
1. __init__
Method
__init__()
method, which is called by default when an object is created and does not need to be called manually. During development, if you want to set the properties of the object while creating the object, you can __init__
modify the method.
class Cat:
"""这是一个猫类"""
def __init__(self,name): # 重写了 `__init__` 魔法方法
self.name = name
def eat(self):
return "%s爱吃鱼"%self.name
def drink(self):
return '%s爱喝水'%self.name
"""
tom = Cat()
TypeError: __init__() missing 1 required positional argument: 'name'
这种写法在运行时会直接报错!因为 `__init__` 方法里要求在创建对象时,必须要传递 name 属性,如果不传入会直接报错!
"""
tom = Cat("Tom") # 创建对象时,必须要指定 name 属性的值
tom.eat() # tom爱吃鱼
Notice:
__init__()
The method will be called by default when the object is created, and there is no need to call this method manually.__init__()
The parameters in the methodself
do not need to pass parameters when creating an object, and the python interpreter will directly assign the created object reference to itself
.- Inside the class, you can use
self
attributes and call methods; outside the class, you need to use the object name to use attributes and call methods. - If there are multiple objects, the attributes of each object are stored separately and have their own independent addresses.
- The method is shared by all objects and only occupies one memory space. When the method is called, it will use to
self
determine which object called the instance method.
2. __del__
Method
After the object is created, the Python interpreter calls __init__()
the method by default; and when the object is deleted, the Python interpreter also calls a method by default, which is the method __del__()
.
class Student:
def __init__(self,name,score):
print('__init__方法被调用了')
self.name = name
self.score = score
def __del__(self):
print('__del__方法被调用了')
s = Student('lisi',95)
del s
input('请输入内容')
3. __str__
Method
__str__
The method returns the description information of the object. print()
When the function is used to print the object, the method of the object is actually called __str__
.
class Cat:
def __init__(self,name,color):
self.name = name
self.color = color
tom = Cat('Tom','white')
# 使用 print 方法打印对象时,会调用对象的 __str__ 方法,默认会打印类名和对象的地址名
print(tom) # `<__main__.Cat object at 0x0000021BE3B9C940>`
If you want to modify the output of the object, you can override __str__
the method.
class Person:
def __init__(self,name,age):
self.name = name
self.age = age
def __str__(self):
return '哈哈'
p = Person('张三',18)
print(p) # 哈哈 打印对象时,会自动调用对象的 `__str__` 方法
In general, when we print an object, we may need to list all the properties of the object.
class Student:
def __init__(self,name,score):
self.name = name
self.score = score
def __str__(self):
return '姓名是:{},成绩是{}分'.format(self.name,self.score)
s = Student('lisi',95)
print(s) # 姓名是:lisi,成绩是95分
4. __repr__
Method
__repr__
The function of the method __str__
is similar to that of the method, both of which are used to modify the default printing content of an object. When printing an object, if __str__
the method is not overridden, it will automatically look for __repr__
the method. If neither of these two methods are available, the memory address of the object will be printed directly.
class Student:
def __init__(self, name, score):
self.name = name
self.score = score
def __repr__(self):
return 'helllo'
class Person:
def __repr__(self):
return 'hi'
def __str__(self):
return 'good'
s = Student('lisi', 95)
print(s) # hello
p = Person()
print(p) # good
5. __call__
Method
Add parentheses after the object to trigger execution.
class Foo:
def __init__(self):
pass
def __call__(self, *args, **kwargs):
print('__call__')
obj = Foo() # 执行 `__init__`
obj() # 执行 `__call__`
Summarize:
- When an object is created,
__init__
the method is called automatically, and when an object is deleted,__del__
the method is called automatically. - Using
__str__
the and__repr__
methods, both modify the result of converting an object to a string. In general,__str__
the result of a method is more about readability, and__repr__
the result of a method is more about correctness (for example: the datetime class in the datetime module).
Advanced case
[Python] Python realizes the word guessing game-challenge your intelligence and luck!
[python] Python tkinter library implements GUI program for weight unit converter
[python] Use Selenium to get (2023 Blog Star) entries
Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition
[Xiaobai must see] Python word cloud generator detailed analysis and code implementation
[Xiaobai must see] Python crawls an example of NBA player data
[Must-see for Xiaobai] Sample code for crawling and saving Himalayan audio using Python
[Xiaobai must see] Python crawler data processing and visualization
[Must-see for Xiaobai] Python crawler program to easily obtain hero skin pictures of King of Glory
[Must-see for Xiaobai] Use Python to generate a personalized list Word document
Geospatial data processing and visualization using geopandas and shapely (.shp)
Use selenium to crawl Maoyan movie list data
Detailed explanation of the principle and implementation of image enhancement algorithm Retinex
Getting Started Guide to Crawlers (8): Write weather data crawler programs for visual analysis
Getting started with crawlers (4): The best way to crawl dynamic web pages using Selenium and API
Getting Started Guide to Crawlers (3): Python network requests and common anti-crawler strategies
Getting started with crawlers (2): How to use regular expressions for data extraction and processing
Getting started with reptiles (1): Learn the basics and skills of reptiles
Python object-oriented programming basics and sample code
MySQL database operation guide: learn how to use Python to add, delete, modify and query operations
Python file operation guide: encoding, reading, writing and exception handling
Selenium Automation Toolset - Complete Guide and Tutorials
Python web crawler basics advanced to actual combat tutorial
Pandas data processing and analysis tutorial: from basics to actual combat
Detailed explanation of commonly used data types and related operations in Python
[Latest in 2023] Detailed Explanation of Six Major Schemes to Improve Index of Classification Model