[Learn python from zero] 40.python magic method (1)

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 method selfdo not need to pass parameters when creating an object, and the python interpreter will directly assign the created object reference to it self.
  • Inside the class, you can use selfattributes 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 selfdetermine 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

[python] Use Selenium and Chrome WebDriver to obtain article information in [Tencent Cloud Studio Practical Training Camp]

Use Tencent Cloud Cloud studio to realize scheduling Baidu AI to realize text recognition

[Fun with Python series [Xiaobai must see] Python multi-threaded crawler: download pictures of emoticon package websites

[Play with Python series] [Must-see for Xiaobai] Use Python to crawl historical data of Shuangseqiu and analyze it visually

[Play with python series] [Must-see for Xiaobai] Use Python crawler technology to obtain proxy IP and save it to a file

[Must-see for Xiaobai] Python image synthesis example using PIL library to realize the synthesis of multiple images by ranks and columns

[Xiaobai must see] Python crawler actual combat downloads pictures of goddesses in batches and saves them locally

[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

[Must-see for Xiaobai] Technical realization of using Python to download League of Legends skin pictures in batches

[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

[Must-see for Xiaobai] Python crawler combat: get pictures from Onmyoji website and save them automatically

Xiaobai must-see series of library management system - sample code for login and registration functions

100 Cases of Xiaobai's Actual Combat: A Complete and Simple Shuangseqiu Lottery Winning Judgment Program, Suitable for Xiaobai Getting Started

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

Introductory Guide to Crawlers (7): Using Selenium and BeautifulSoup to Crawl Douban Movie Top250 Example Explanation [Reptile Xiaobai must watch]

Getting Started Guide to Crawlers (6): Anti-crawlers and advanced skills: IP proxy, User-Agent disguise, Cookie bypass login verification and verification code identification tools

Introductory Guide to Crawlers (5): Distributed Crawlers and Concurrency Control [Implementation methods to improve crawling efficiency and request rationality control]

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

Application of Deep Learning Model in Image Recognition: CIFAR-10 Dataset Practice and Accuracy Analysis

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

Use Python and Selenium to automate crawling#【Dragon Boat Festival Special Call for Papers】Explore the ultimate technology, and the future will be due to you"Zong" #Contributed articles

Python multi-thread and multi-process tutorial: comprehensive analysis, code cases and optimization skills

Selenium Automation Toolset - Complete Guide and Tutorials

Python web crawler basics advanced to actual combat tutorial

Python introductory tutorial: master the basic knowledge of for loop, while loop, string operation, file reading and writing and exception handling

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

Introductory Python programming basics and advanced skills, web development, data analysis, and machine learning and artificial intelligence

Graph prediction results with 4 regression methods: Vector Regression, Random Forest Regression, Linear Regression, K-Nearest Neighbors Regression

Guess you like

Origin blog.csdn.net/qq_33681891/article/details/132355786