Home Backend Development Python Tutorial Code tutorial for Python operator overloading

Code tutorial for Python operator overloading

May 15, 2017 am 11:34 AM

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

##initObject creation: X = Class(args)delX object is recoveredadd/subAddition and subtraction operations X+Y, X+=Y/X-Y, X-=Y##or_repr/strcallgetattrAttributesetattrdelattrDelete##getattributegetitem],X[i:j]setitemdelitemlenboollt, gt, le, ge, X==Y,X!=Y Right side addition##iaddField (enhanced) addition add)IteratecontainsMembership testValue##with obj as var:deleteDescriptor attribute
##Method name

Overloading description

Operator calling method

Constructor

Destructor

Operator|

X|Y, X|= Y

Print/Convert

print (X)、repr(X)/str(X)

Function call

X(*args, **kwargs)

Quote

X.undefined

Attribute assignment

X.any=value

Attribute

del X.any

Attribute get

X.any

Index operation

X[

key

Index assignment

X[key],X[ i:j]=sequence

Index and shard deletion

del X[key],del X[i:j]

length

len(X)

Boolean test

bool(X)

eq, ne

Specific comparison

The order is XY,X<=Y,X>= Y,

Note

:(lt: less than, gt: greater than, less equal, ge: greater equal,

eq: equal, ne: not equal )

##radd

other+X

X+=Y(or

else

iter, next

I=iter(X), next ()

item in X (X is any iterable object)

##index

##Integer

hex(X), bin(X), oct(X)

enter, exit

Environment Manager

get, set,

X.attr, X.attr=value, del X.attr

new

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(&#39;Tim&#39;) 
init Tim 
>>> h = &#39;a&#39; 
del
Copy after login

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
Copy after login

String of the objectExpression form: repr and str

## These two methods are used to represent the characters of the object String expression form: The print() and str() methods will call the str method, and the print(), str() and repr() methods will call the repr method. As can be seen from the example below, when two methods are defined at the same time, Python will give priority to searching and calling 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) 
&#39;repr called&#39; 
>>> str(s) 
&#39;str called&#39;
Copy after login

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]
Copy after login

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()
Copy after login

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

variable

x; when init is called, the value will be assigned The operation also calls the setattr method.

Iterator object: iter, next


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
Copy after login

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 S

top

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
Copy after login

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
Copy after login

It can be seen that after implementing the iter and next methods, you can iterate through for in

Traverse the object

You 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 Tutorial

3.

Python Basics Introduction Tutorial

The 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1262
29
C# Tutorial
1235
24
Python vs. C  : Applications and Use Cases Compared Python vs. C : Applications and Use Cases Compared Apr 12, 2025 am 12:01 AM

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

The 2-Hour Python Plan: A Realistic Approach The 2-Hour Python Plan: A Realistic Approach Apr 11, 2025 am 12:04 AM

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python: Games, GUIs, and More Python: Games, GUIs, and More Apr 13, 2025 am 12:14 AM

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

How Much Python Can You Learn in 2 Hours? How Much Python Can You Learn in 2 Hours? Apr 09, 2025 pm 04:33 PM

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

Python vs. C  : Learning Curves and Ease of Use Python vs. C : Learning Curves and Ease of Use Apr 19, 2025 am 12:20 AM

Python is easier to learn and use, while C is more powerful but complex. 1. Python syntax is concise and suitable for beginners. Dynamic typing and automatic memory management make it easy to use, but may cause runtime errors. 2.C provides low-level control and advanced features, suitable for high-performance applications, but has a high learning threshold and requires manual memory and type safety management.

Python and Time: Making the Most of Your Study Time Python and Time: Making the Most of Your Study Time Apr 14, 2025 am 12:02 AM

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python: Exploring Its Primary Applications Python: Exploring Its Primary Applications Apr 10, 2025 am 09:41 AM

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

Python: Automation, Scripting, and Task Management Python: Automation, Scripting, and Task Management Apr 16, 2025 am 12:14 AM

Python excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.

See all articles