This article mainly introduces the detailed explanation of Python operator overloading and related information of example code. Friends who need it can refer to
Python operator overloading
Provided by Python language It has the operator overloading function and enhances the flexibility of the language. This is somewhat similar to but somewhat different from C++. In view of its special nature, today we will discuss Python operator overloading.
The Python language itself provides many magic methods, and its operator overloading is achieved by rewriting these Python built-in magic methods. These magic methods all start and end with double underscores, similar to the form of X. Python uses this special naming method to intercept the operator to achieve overloading. When Python's built-in operations are applied to class objects , Python will search and call the specified method in the object to complete the operation.
Classes can overload built-in operations such as addition and subtraction, printing, function calls, index, etc. Operator overloading makes the behavior of our objects Same as built-in objects. Python will automatically call such a method when calling an operator. For example, if a class implements the add method, this method will be called when an object of the class appears in the + operator.
Common operator overloading methods
##Method name | Overloading description | Operator calling method |
Constructor | Object creation: X = Class(args)||
Destructor | X object is recovered||
Addition and subtraction operations | X+Y, X+=Y/X-Y, X-=Y | |
Operator| | X|Y, X|= Y | |
Print/Convert | print (X)、repr(X)/str(X) | |
Function call | X(*args, **kwargs) | |
Attribute | X.undefined | |
Attribute assignment | X.any=value | |
Attribute | Deletedel X.any | ##getattribute |
Attribute get |
X.any |
getitem |
Index operation |
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, |
eq, ne Specific comparison |
The order is X | X==Y,X!=Y
Note :(lt: less than, gt: greater than, less equal, ge: greater equal, ##radd |
other+X | ##iadd | Field (enhanced) addition |
X+=Y(or else | add)iter, next |
|
contains | Membership test | |
item in X (X is any iterable object) |
##index | ##Integer | Value
hex(X), bin(X), oct(X) |
Environment Manager |
|
get, set, | delete||
X.attr, X.attr=value, del X.attr | ||
create |
before init Create Object |
The following is an introduction to the use of commonly used operator methods.
Constructor and destructor: init and del
Their main function is to create and recycle objects. When an instance is created , the initConstructor Method will be called. When the instance object is reclaimed, the destructor del will be executed automatically.
>>> 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
Addition and subtraction operations: add and sub
Overloading these two methods can add +- operator operations to ordinary objects. The following code demonstrates how to use the +- operator. If you remove the sub method in the code and then call the minus operator, an error will occur.
>>> 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 10 >>> c - 3 2
String of the objectExpression form: repr and str
>>> 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 acquisition and assignment: getitem, setitem
## By implementing these two methods, objects can be processed in the form such as X[i] Get and assign values, and you can also use slicing 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 >>> i[1:4] [2, 3, 4] >>> i[0]=10 [10, 2, 3, 4, 5, 6]
Set and access attributes: getattr, setattr
We can intercept access to object members by overloading getattr and setattr. getattr is automatically called when accessing a member that does not exist in the object. The setattr method is used to call when initializing object members, that is, the setattr method will be called when setting the dict item. The specific example is 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(1,2) a.f() a.x a.x = 3 a.f()
The running results of the above code are as follows. From the results, it can be seen that the getattr method will be called when accessing the non-existent
variablex; when init is called, the value will be assigned The operation also calls the setattr method. setattr
setattr
{'a': 1, 'b': 2}
getattr
setattr
{'a': 1, 'x': 3, 'b': 2}
Iteration in Python can be implemented directly by overloading the getitem method. See the example below.
>>> 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
Iteration can be achieved through the above method, but it is not the best way. Python's iteration operation will first try 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, which returns an iterator object. If this method is provided, Python will repeatedly call the next() method of the iterator object until the Stop
Iteration exception occurs. If iter is not found, Python will try 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(self): return self def next(self): print("next called") if self.data > 5: raise StopIteration else: self.data += 1 return self.data for i in Next(3): print(i) print("-----------") n = Next(3) i = iter(n) while True: try: print(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
It can be seen that after implementing the iter and next methods, you can iterate through for in
Traverse the objectYou can also iterate through the object through the iter() and next() methods. 【Related Recommendations】
1.
Special Recommendation: "php Programmer Toolbox" V0.1 version download2.
Python Free Video TutorialPython Basics Introduction TutorialThe above is the detailed content of Code tutorial for Python operator overloading. For more information, please follow other related articles on the PHP Chinese website!

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 English version
Recommended: Win version, supports code prompts!

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
