In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article introduces you what are the magic methods in python, the content is very detailed, interested friends can refer to, hope to be helpful to you.
Magic method list basic method
_ _ new__ (cls,*args,kwargs) creates the class method first called by the instance, and cls refers to this class. Note the writing of * args and kwargs. If not, the _ _ init__ method will not receive the parameter _ _ init__ (self [, …]) Constructor, create instance method _ _ del__ (self) destructor, destroy instance method _ _ call__ (self [, args...]) Allow instances to be called like functions That is, the essence of running "instance ()" is to call the instance's _ _ call__ method _ _ len__ (self) definition when called by len (), the method _ _ repr__ (self) definition when called by repr (), the method _ _ str__ (self) definition when called by str (), the method _ _ bytes__ (self) definition when called by bytes (), the method _ _ hash__ (self) definition when called by bytes (). Method _ _ bool__ (self) when called by hash () defines the method when called by bool () Must return True or False__format__ (self,format_spec) to define the method property method when called by format ()
_ _ getattr__ (self,name) defines the method when accessing a property that does not exist _ _ getattribute__ (self,name) defines the method when accessing the specified property _ _ setattr__ (self,name,value) defines the method when modifying the specified property _ _ delattr__ (self,name) defines the method when deleting the specified property _ _ dir__ (self) defines the method _ _ get__ when called by dir () (self,instance) Owner) defines the method _ _ set__ (self,instance,value) when the value of the descriptor is obtained. Defines the method _ _ delete__ (self,instance) when the value of the descriptor is changed. Defines the method comparison operator when the value of the descriptor is deleted.
_ _ lt__ (self,other) defines the method of the less than sign: Xroomy invokes the x.arithmetic _ (y) arithmetic operator
_ _ add__ (self,other) defines the method of addition: +. For example, xroomy is essentially the _ _ add__ method of finding x; if it is found, it executes x.destroy _ _ (y); if x does not have a _ _ add__ method, it looks for the _ _ radd__ method of y; if y does not have a _ _ radd__ method, it will report an error. _ _ sub__ (self,other) defines the method of subtraction:-_ _ mul__ (self,other) defines the method of multiplication: * _ _ truediv__ (self,other) defines the method of true division: /, this function works only when from__future__importdivision is used. _ _ div__ (self,other) defines the method of division: / _ _ floordiv__ (self,other) defines the method of division rounding: / / _ _ mod__ (self,other) defines the method of division remainder:% _ _ divmod__ (self,other) defines the method when called by divmod (). Divmod is division, and the returned value is the tuple, which has two items. The first item is the result of division rounding, and the second item is the result of division remainder. _ _ pow__ (self,other [, modulo]) defines the method when called by power () or * * operation _ _ lshift__ (self,other) defines the method of bitwise left shift: _ _ and__ (self,other) defines bitwise and operational methods: & _ _ xor__ (self,other) defines bitwise XOR methods: ^ _ or__ (self,other) defines bitwise or operational methods: | right arithmetic operator
The _ _ radd__ (self,other) is the same as the arithmetic operator above, the method that the right Operand will call when the left Operand cannot call the arithmetic operator, for example: X _ add__, when x does not have a _ _ add__ method, it will try to call the _ _ radd__ method of y, that is, execute the _ _ arithmetic _ (y), and an error will be reported if y does not have _ _ radd__ either. _ _ rsub__ (self,other) ditto _ _ rmul__ (self,other) ditto _ _ rtruediv__ (self,other) ditto _ _ rdiv__ (self,other) ditto _ _ rfloordiv__ (self,other) ditto _ _ rmod__ (self,other) ditto _ rdivmod__ (self,other) ditto _ rpow__ (self,other) ditto _ rlshift__ (self,other) ditto _ rrshift__ (self,other) ditto _ rand__ (self) Other) ditto _ _ rxor__ (self,other) ditto _ _ ror__ (self,other) ditto incremental assignment operation
_ _ iadd__ (self,other) defines the method of assignment addition: + = _ _ isub__ (self,other) defines the method of assignment subtraction:-= _ _ imul__ (self,other) defines the method of assignment multiplication: * = _ _ itruediv__ (self,other) defines the method of assignment true division: / = _ _ ifloordiv__ (self,other) defines the method of assignment integer division: / / = _ _ division (self) Other) defines the method of assignment modularization algorithm:% = _ ipow__ (self,other [, modulo]) defines the method of exponentiation of assignment: = _ _ ilshift__ (self,other) defines the method of left shift of assignment by bit: = _ iand__ (self,other) defines the method of bitwise and operation of assignment: & = _ ixor__ (self,other) defines the method of bitwise exclusive or operation of assignment: ^ = _ ior__ (self) Other) defines the bitwise or operational method of assignment: | = unary operator
_ _ pos__ (self) defines the positive sign method: + x inverse negative sign _ (self) defines the method of the minus sign:-x inverse negativity _ (self) defines the method _ _ invert__ (self) when called by abs () defines the bitwise inversion method: ~ x type conversion
_ _ complex__ (self) defines the method when called by complex () (needs to return the appropriate value) _ _ int__ (self) defines the method when called by int () (needs to return the appropriate value) _ _ float__ (self) defines the method when called by float () (needs to return the appropriate value) _ _ round__ (self [ N]) defines the method (which needs to return the appropriate value) _ _ index__ (self) 1 when called by round (). When the object is applied to the slice expression, implement shaping cast 2. If you define a custom numeric type that may be used in slicing, you should define _ _ index__3. If _ _ index__ is defined, _ _ int__ also needs to be defined and returns the same value context management (with statement)
_ _ enter__ (self) 1. Define the initialization behavior when using the with statement. The return value of with _ is bound by the target of the as statement or by the name after as _ _ exit__ (self,exc_type,exc_value,traceback) 1. Defines what the context manager should do when a code block is executed or terminated. It is generally used to handle exceptions, clean up work, or do some routine work after the code block has been executed.
_ _ len__ (self) defines the method when called by len () (returns the number of elements in the container) _ _ getitem__ (self,key) defines the method to get the specified element in the container, which is equivalent to self [key] _ _ setitem__ (self,key,value) defines the method to set the specified element in the container, and self [key] = value__delitem__ (self,key) defines the method to delete the specified element in the container. Equivalent to delself [key] _ _ iter__ (self) defines the method _ _ reversed__ (self) of the elements in the iteration container when the method _ _ contains__ (self,item) is called by reversed () defines the method magic method explanation when using the member test operator (in or notin)
Magic methods have written two articles before, and this is the last one. The difficulties have been basically covered, and most of the remaining magic methods are various operators. Here is a simple example of operator overloading.
Operator overloading
Here is a small case of operator overloading.
There is a soldier-to-soldier game in which the blue army is special forces (attack power 30, health 99), and the red army is veteran (attack power 20, health 80).
The blue army must win the game against the red army, right? Don't worry, now the leader of the Red Army also thought of it, so she assigned a nurse to the veteran of the Red Army (attack power 18, health 80). The nurse's attack power was relatively low, but she could treat the veteran.
Class Soldier:def _ init__ (self, name, attack, health): self.name = name self.attack = attack self.health = healthdef _ add__ (self, other): other.health + = self.attackdef _ sub__ (self, other): other.health-= self.attackblue = Soldier ('Blue Bing', 30, 99) red = Soldier ('Red Bing', 20, 80) red_nurse = Soldier ('Red Guard', 18 80) while blue.health > 0 and red.health > 0:red-blue blue-red red_nurse + redprint (f "Red Army veterans still have {red.health} blood left!") Print (f "Blue Army Special Forces Blood volume is {blue.health}, has been killed!") Out: veterans of the Red Army still have 20:00 blood left! The blood volume of the Blue Army Special Forces is-1, has been killed! About the magic methods in python which are shared here, I hope the above content can help you to a certain extent, you can learn more knowledge. If you think the article is good, you can share it for more people to see.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.