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

Python explains magic methods in depth

編輯:Python

Catalog

One 、python Built in basic magic methods

Two 、python Magic method of container type in

3、 ... and 、python Magic method of arithmetic operator in

What is the magic method ( Magic methods / Special methods )

Magic methods don't need to be called manually

It is triggered under certain circumstances

Magic methods are all in python Defined in advance , When defining methods , Don't use magic naming conventions

The magic method is to start with a double dash , Ending with a double dash

One 、python Built in basic magic methods

init Method

init Is the method of class instantiation

# for example class Mytest(): def __init__(self): print("---- This is magic __init__")Mytest()

call Method

__call__ The role of methods : The implementation object is callable

1. It didn't come true __call__ When the method is used , Objects are not callable

# class class Demo: pass# Determine whether the object can be called , There is a function that can use ——callableprint(callable(Demo)) ======》 return True, Can be called # demo Class can be called , Cannot be called obj = Demo()obj()

Execution results : Tips :‘Demo’ object is not callable ----- No, __call__ Method

2. If you want to create an object from a class, do not call , You use __call__ Method

class Demo: def __call__(self, *args,**kwds): print(" This is a __call__ Method executed ")print(callable(Demo))# demo Class can be called ( Cannot be called )obj = Demo()obj() # Equate to :obj.__call__() Method obj()obj()

new Method

__new__ The role of methods : Is the method of creating objects

__init__ The role of methods : Is a method used to initialize an object

The object of the class should be able to be called :

first new Method to create an object , And then through init Method initialization

When will I need it New Method :

Intervene in the process of class instantiating objects

Be careful :

Generally, do not rewrite new Method , Unless there is a specific need to use new Method to implement

Defined new After method , You need to call the new To create objects And back to

class MyTest(object): # Initialize object def __init__(self): print('-------init------ Method ')# Create objects def __new__(cls, *args, **kwargs): print('------new Method -------') obj = super().__new__(cls) # Calling the new To create objects return obj # And return a new object obj = MyTest()

bool(self) Method

Definition should be bool() Behavior at call time , Should return to True or False

class Demo: def __bool__(self): """ Built in functions bool(), Getting the Boolean value of an object will execute this method """ return Trueb = Demo() # Gets the Boolean value of the object , return True or Falseprint(bool(b)) =====》 return True

str(self) Method

Use print When exporting objects , The content output to the console is generated by __str__ To decide

class Demo: def __str__(self): """ Use print When exporting objects , The content output to the console is generated by __str__ To decide """ return 'zifuc'b = Demo() # str Method s = str('123')print(s) =======》 return 123

repr(self) Method

This method also controls the display of objects , Generally, the original information of the object will be displayed

class Demo: def __repr__(self): """ This method also controls the display of objects , Generally, the original information of the object will be displayed """ return 'repr-number'b = Demo() # repr Method s = repr('123')print(s) =======》 return '123'

len(self) Method

Get the length of the object

class Demo: def __len__(self): """ This method is to get the length of the object :return: """ return 3 b = Demo() # Get the length of the object print(len(b)) =====》 return 3

hash(self) Method

Return object's hash value

class Demo: def __hash__(self): """ This method is to get hash value :return: """ return 999b = Demo() # obtain hash value print(hash(b)) =====》 return 999 Two 、python Magic method of container type in

setitem(self, key, value) Method

Defines the behavior of the specified element in the settings container , grammar :self[key] = value

class Mytest: def __setitem__(self, key, value): return setattr(self, key, value)m = Mytest()print(m.__dict__) No data , Empty dictionary m.name = 'gddg' ==== 》 Set up name attribute , The value is gddgm['age'] = 18 ==== 》 Set up age attribute , The value is 18

getitem(self, item) Method

Defines the behavior of getting the specified elements in the container , grammar : self[key]

class Mytest: def __getitem__(self,item): return getattr(self,item)m = Mytest()print(m['name']) ==== 》 name attribute , The value is gddg

delitem(self, item) Method

Defines the behavior of deleting a specified element in a container , amount to del self[key]

class Mytest: def __delitem__(self,item): delattr(self,item)m = Mytest()del m['name'] ==== 》 Delete name attribute

contains(self, item) Method

Define when using member test operators (in or not in) The behavior of time , return True or False

class MyTest: def __contains__(self, item): """ Magic method triggered by member operator """ return Truea = MyTest()b = MyTest()print(a in b) =======》 return True

Iterative protocol :__iter__ Method

Define the behavior of elements in the iteration container

class IterClass: def __iter__(self): """ __iter__ The return value of a method must be an iterator """ return iter([11, 22, 33, 44]) ===== 》 Returns an iterator li = IterClass()for i in li :print(i )for Traversing objects : 1、 Of the execution object __iter__ Method ( Return iterator ) 2、 In recycling next Iterate over iterators 3、 ... and 、python Magic method of arithmetic operator in

add(a,b) Method and sub(a,b) Method

a = 1b = 2print(a + b) ======》 What is actually carried out is :a.__add__(a,b)print(a - b) ======》 What is actually carried out is :a.__sub__(a,b)

Whether the string type supports addition and subtraction

a = '123'b = '12'print(a + b) ======》 What is actually carried out is :a.__add__(a,b)print(a - b) ======》 What is actually carried out is :a.__sub__(a,b)

There is no implementation for string objects __sub__ Method , Therefore, direct use of objects is not supported -

I am redefining __sub__ Method , Implement subtraction of string objects

class MyStr(str): def __sub__(self, other): return self.replace(other, '')a = MyStr('1234')b = MyStr('123')print(a + b) ======= 》 return 1234123print(a - b) ======= 》 return 4

This is about python This is the end of the article on magic methods , More about python Magic method content please search the previous articles of the software development network or continue to browse the relevant articles below. I hope you will support the software development network in the future !



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