程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python: introduction to magic methods (\u getitem\u, \u len\u and other methods composed of double underscores) and detailed introduction to use cases

編輯:Python

Python: Magic methods (__getitem__、__len__ And other methods that contain double underscores ) An introduction to the 、 Detailed introduction to use cases

Catalog

Magic methods Magic Method An introduction to the

(1)、 For example, to understand Magic Method

Common magic method use cases

1、 Common methods

(1)、__init__: Initialization method

(2)、__len__(): Returns the number of elements in the container

2、 Comparison operator

(1)、__lt__(self, other): Define the behavior of the less than sign

3、 Arithmetic operator

(1)、__add__(self, other): The act of defining addition :+

4、 Incremental assignment operation

(1)、__iadd__(self, other): Define the behavior of assignment addition :+=

5、 Unary operators

(1)、__pos__(self): Define positive behavior :+x

6、 Container type

(1)、_getitem__(): Return the value of the key


Magic methods Magic Method An introduction to the

       Magic Method, Magic method , seeing the name of a thing one thinks of its function , These methods are powerful , Full of magic , Can let you realize many functions . The magic method is python Built-in methods , No active call required , The purpose of existence is to to python The interpreter of , Almost every magic method has a built-in function , Or operator , When we use these functions or operators on this object, we will call the corresponding magic methods in the class , It can be understood as Rewrite these python Built in functions for .

(1)、 For example, to understand Magic Method

        stay Python in , image __getitem__ This method consists of two double underscores , Unification is called the magic method . The magic method is to give python The interpreter uses . Magic methods are methods belonging to classes , All of them operate on classes . That is, the method can be accessed without instantiating the class , meanwhile , All instantiated objects can access this method .
For example, when using len(function) when , It's actually called object.__len__ Method . But in the use of function['key'] To access the element , It's actually calling theta object.__getitem__(key) Method .
Use __getitem__ and __len__ Method , We can implement an iteration and access to custom data types .

Common magic method use cases

1、 Common methods

(1)、__init__: Initialization method

Constructors , Initialization method called when an instance is created

class Test_init:
def __init__(self):
print(" One of the magic methods __init__ Method ")
print(Test_init())


(2)、__len__(): Returns the number of elements in the container

To make... For an object instance of a class len() Function executed successfully , Must be defined in the class __len__(). If there is no definition __len__(), Then input len(c1) It will prompt you to make mistakes , Obviously the reason for the mistake is Class01 There is no len() The definition of . because len() You must receive the properties of a specific instantiated object , If change to len(c1.values) Can also successfully execute !

# __ len__(): Returns the number of elements
class Test_len(object):
def __init__(self, *args):
self.names = args
def __len__(self):
print(" One of the magic methods __len__ Method ")
return len(self.names)
res02 = Test_len('Bob', 'Alice', 'Tom')
print(len(res02))

2、 Comparison operator

(1)、__lt__(self, other): Define the behavior of the less than sign

x < y call x__lt__(y)


3、 Arithmetic operator

(1)、__add__(self, other): The act of defining addition :+

4、 Incremental assignment operation

(1)、__iadd__(self, other): Define the behavior of assignment addition :+=

5、 Unary operators

(1)、__pos__(self): Define positive behavior :+x

6、 Container type

(1)、_getitem__(): Return the value of the key

If this is defined in the class __getitem__ Method , Then its instance object ( Is assumed to be p), It can be like this p[key] Value . When instance objects do p[key] Operation time , Will call the methods in the class __getitem__.__getitem __ You can let objects implement iterative functions , In this way, the data can be called continuously .

class Test_getitem:
def __init__(self,id):
self.id=id
# , Its instance object P, We can use P[key] Formal value
def __getitem__(self, item): # When instance objects do P[key] Operation time , It will call __getitem__() Method
print(" One of the magic methods __getitem__ Method ")
return self.id
res = Test_getitem('This is id')
print(res.id)
print(res[0]) # When instance objects do P[key] Operation time , It will call __getitem__() Method
print(res['0000'])


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved