This article mainly introduces the Python operator overload and the example code of the relevant information, the need for friends can refer to the following
Python operator overloading
The Python language provides operator overloading, which enhances the flexibility of the language, which is somewhat similar to C + + and somewhat different. In view of its particularity, we will discuss Python operator overloading today.
The Python language itself provides a number of magical methods, and its operator overloading is achieved by rewriting these python built-in magic methods. These magic methods are both beginning and ending with a double underscore, similar to the form of X, in which Python intercepts the operator for overloading by this special naming scheme. When Python's built-in operations are applied to the class object, Python searches for and invokes the method specified in the object to complete the operation.
Classes can overload built-in operations such as add and subtract operations, printing, function calls, indexes, and operator overloading to make our objects behave the same as built-in objects. Python calls this method automatically when the operator is called, for example, if the class implements the Add method, which is called when the object of the class appears in the + operator.
Common operator overloading methods
Method name |
Overloading instructions |
Operator Invocation method |
Init |
constructor function |
Object creation: X = Class (args) |
Del |
Destructors |
X Object retract |
Add/sub |
Add and subtract operations |
X+y, X+=y/x-y, x-=y |
Or |
operator | |
X| Y, X|=y |
_repr/str |
Print/Convert |
Print (x), repr (x)/str (x) |
Pager |
Function call |
X (*args, **kwargs) |
GetAttr |
Property Reference |
x.undefined |
SetAttr |
Property Assignment Value |
X.any=value |
Delattr |
Property Delete |
Del X.any |
GetAttribute |
Property gets |
X.any |
GetItem |
Index operations |
X[KEY],X[I:J] |
SetItem |
Index Assignment |
X[key],x[i:j]=sequence |
Delitem |
Index and Shard deletion |
Del X[key],del X[i:j] |
Len |
Length |
Len (X) |
bool |
Boolean test |
BOOL (X) |
LT, GT, Le, GE, EQ, NE |
A specific comparison |
X<y,x>y,x<=y,x>=y in turn, X==y,x!=y Note: (lt:less than, gt:greater than, le:less equal, Ge:greater equal, Eq:equal, Ne:not Equal ) |
Radd |
Right addition |
Other+x |
Iadd |
field (Enhanced) addition |
X+=y (or else add) |
ITER, Next |
Iteration |
I=iter (X), Next () |
Contains |
Member Relationship Testing |
item in x (X is any object that can be iterated) |
Index |
Integer value |
Hex (x), Bin (x), Oct (x) |
Enter, exit |
Environment Manager |
With obj as Var: |
Get, set, Delete |
Descriptor Properties |
X.attr, X.attr=value, Del x.attr |
New |
Create |
Create an object before Init |
The following is an introduction to the use of commonly used operator methods.
Constructors and destructors: Init and Del
Their primary role is to create and reclaim objects, and when the instance is created, the Init constructor method is called. When an instance object is retracted, the destructor del is automatically executed.
>>> class Human (): ... Def init (self, n): ... Self.name = N ... Print ("Init", Self.name) ... Def del (self): ... Print ("del") ... >>> h = Human (' Tim ') init Tim >>> h = ' a ' del
Add and subtract operations: add and Sub
Overloading these two methods allows you to add the + + operator action on a normal object. The following code shows how to use the-+ operator, and if you remove the sub method from the code, then the minus operator is called an error.
>>> class computation (): ... def init (self,value): ... Self.value = value ... def add (self,other): ... Return Self.value + other ... def sub (self,other): ... Return Self.value-other ... >>> C = Computation (5) >>> C + 5 >>> c-3 2
The string representation of the object: Repr and Str
Both methods are used to represent the string representation of an object: the print (), str () method calls to the Str method, and the print (), str (), and repr () methods call the Repr method. As can be seen in the following example, when two methods are defined at the same time, Python will first search and invoke the Str method.
>>> class Str (object): ... def str (self): ... Return "str called" ... def repr (self): ... Return "repr called" ... >>> s = str () >>> print (s) str called >>> repr (s) ' repr called ' >>> str (s) ' Str called '
Index value and Assignment: GetItem, SetItem
By implementing these two methods, you can value and assign objects in the form of x[i], and you can use slice operations on objects.
>>> class Indexer: data = [1,2,3,4,5,6] def getitem (self,index): return Self.data[index] def setitem (self,k,v): self.data[k] = v print (self.data) >>> i = Indexer () >>> i[0] 1 >>& Gt I[1:4] [2, 3, 4] >>> i[0]=10 [10, 2, 3, 4, 5, 6]
Settings and Access properties: GetAttr, SetAttr
We can block access to object members by overloading GetAttr and SetAttr. GetAttr is called automatically when accessing a member that does not exist in the object. The SetAttr method is used to invoke when initializing an object member, that is, the SetAttr method is called when the Dict item is set. Specific examples are as follows:
Class A (): def init (SELF,AX,BX): self.a = ax self.b = bx def f (self): print (self.dict) def GetAttr (self,name): print ("GetAttr") def setattr (self,name,value): print ("SetAttr") Self.dict[name] = value a = A (A.F) a.x a.x = 3 A.F ()
The result of the above code is as follows, as you can see from the results, the GetAttr method is called when the non-existent variable x is accessed, and the assignment operation calls the SetAttr method when Init is called.
SetAttr setattr {' A ': 1, ' B ': 2} getattr setattr {' A ': 1, ' X ': 3, ' B ': 2}
Iterator object: ITER, Next
The iterations in Python can be implemented directly by overloading the GetItem method, as shown in the following example.
>>> class Indexer: ... data = [1,2,3,4,5,6] ... def getitem (self,index): ... Return Self.data[index] ... >>> x = Indexer () >>> for item in x: ... Print (item) ... 1 2 3 4 5 6
It is possible to iterate through the methods above, but not the best way. The Python iteration will first attempt to call the Iter method, and then try to getitem. The iterative environment is implemented by using ITER to try to find the ITER method, and this method returns an Iterator object. If this method is already provided, Python will repeatedly invoke the next () method of the iterator object until the stopiteration exception occurs. If Iter,python is not found, it will attempt to use the GetItem mechanism. Let's look at an example of an iterator.
Class Next (object): def init (self, data=1): self.data = Data def ITER: return self def Next ( Self): print ("next called") if Self.data > 5: raise stopiteration else: self.data + = 1 Return self.data for I under Next (3): Print (i) Print ("-----------") n = Next (3) i = ITER (n) while True: try: p Rint (Next (i)) except Exception as E: break
The running results of the program are as follows:
Next called 4 next called 5 next called 6 next called-----------next called 4 next called 5 next called 6 next called
After the ITER and next methods are implemented, you can iterate through the objects in the for-in way, or iterate through the objects through the ITER () and Next () methods.
"Recommended"
1. Special recommendation : "PHP Programmer Toolkit" V0.1 version download
2. Python Free video tutorial
3. Python Basics Getting Started tutorial