Python dainganxanh
  • Lời nói đầu
  • Chương I. SƠ LƯỢC
    • Bài 1. Cài đặt môi trường
    • Bài 2. Từ khóa và định danh
    • Bài 3. Câu lệnh, khối lệnh và chú thích
    • Bài 4. Nhập, xuất dữ liệu
    • Bài 5. Toán tử và lệnh gán
    • Bài 6. Biến, Hằng
    • Bài 7. Kiểu dữ liệu
    • Bài 8. Thao tác với tệp (cơ bản)
    • Bài 9. Tổng quan về Python
    • Bài tập chương 1
  • Chương II. RẼ NHÁNH - LẶP
    • Bài 10. Cấu trúc rẽ nhánh if…else
    • Bài 11. Cấu trúc lặp với for
    • Bài 12. Cấu trúc lặp với while
    • Bài 13. Lệnh break và continue
    • Bài tập chương 2
  • Chương III. HÀM & MODULE
    • Bài 14. Hàm
    • Bài 15. Tham số hàm
    • Bài 16. Đệ quy
    • Bài 17. Hàm ẩn danh
    • Bài 18. Biến toàn cục và cục bộ
    • Bài 19. Module
    • Bài 20. Package
  • Chương IV. KIỂU DỮ LIỆU
    • Bài 21. Dữ liệu kiểu số
    • Bài 22. Dữ liệu kiểu string
    • Bài 23. Dữ liệu kiểu list
    • Bài 24. Dữ liệu kiểu tuple
    • Bài 25. Dữ liệu kiểu set
    • Bài 26. Dữ liệu kiểu dictionary
  • Chương V. TỆP & THƯ MỤC
    • Bài 27. Đọc và ghi file
    • Bài 28. Quản lý file và folder
  • Chương VI. LỖI & NGOẠI LỆ
    • Bài 29. Ngoại lệ
    • Bài 30. Xử lý ngoại lệ
    • Bài 31. Xây dựng ngoại lệ
  • Chương VII. HƯỚNG ĐỐI TƯỢNG
    • Bài 32. Lập trình hướng đối tượng
    • Bài 33. Đối tượng và Lớp
    • Bài 34. Kế thừa
    • Bài 35. Đa kế thừa
    • Bài 36. Nạp chồng toán tử
  • Chương VIII. NGÀY - GIỜ
    • Python datetime
    • Python strftime()
    • Python strptime()
    • Current date and time
    • Get Current time
    • Timestamp to datetime
    • Python time Module
    • Python sleep()
  • Chương IX. CHỦ ĐỀ NÂNG CAO
    • Python Iterators
    • Python Generators
    • Python Closures
    • Python Decorators
    • Python @property decorator
    • Python RegEx
    • Python Examples
  • PHỤ LỤC - GHI CHÉP
    • Hàm map()
    • Cài Sublime Text để code Python
    • Ghi chép - ghi chú
    • Mảng 2 chiều
    • Công thức với dãy số
  • Tài liệu tham khảo
  • www.dainganxanh.com
  • 🐍Khóa học Python
  • 🤷‍♀️Hỏi đáp, chia sẻ (FG)
  • 🎮Sinh Test chấm Themis
Powered by GitBook
On this page
  • Nạp chồng toán tử trong Python
  • Python Special Functions
  • Overloading the + Operator
  • Overloading Comparison Operators

Was this helpful?

  1. Chương VII. HƯỚNG ĐỐI TƯỢNG

Bài 36. Nạp chồng toán tử

Python Operator Overloading

PreviousBài 35. Đa kế thừaNextChương VIII. NGÀY - GIỜ

Last updated 4 years ago

Was this helpful?

You can change the meaning of an operator in Python depending upon the operands used. In this tutorial, you will learn how to use operator overloading in Python Object Oriented Programming.

Ta có thể thay đổi ý nghĩa của một toán tử trong Python tùy thuộc vào các toán hạng được sử dụng. Trong bài này ta sẽ học cách sử dụng nạp chồng toán tử trong Lập trình hướng đối tượng Python.

Nạp chồng toán tử trong Python

work for built-in classes. But the same operator behaves differently with different types. For example, the + operator will perform arithmetic addition on two numbers, merge two lists, or concatenate two strings.

Các toán tử Python hoạt động đối với các lớp dựng sẵn. Nhưng cùng một toán tử hoạt động khác nhau với các kiểu khác nhau. Ví dụ: toán tử + sẽ thực hiện phép cộng số học trên hai số, hợp nhất hai danh sách hoặc nối hai chuỗi .

This feature in Python that allows the same operator to have different meaning according to the context is called operator overloading.

Tính năng này trong Python cho phép cùng một toán tử có nghĩa khác nhau tùy theo ngữ cảnh được gọi là nạp chồng toán tử

So what happens when we use them with objects of a user-defined class? Let us consider the following class, which tries to simulate a point in 2-D coordinate system.

Vậy điều gì sẽ xảy ra khi chúng ta sử dụng chúng với các đối tượng của một lớp do người dùng định nghĩa? Chúng ta hãy xem xét lớp sau, lớp này mô phỏng một điểm trong hệ tọa độ 2-D.

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y


p1 = Point(1, 2)
p2 = Point(2, 3)
print(p1+p2)

Output

Traceback (most recent call last):
  File "<string>", line 9, in <module>
    print(p1+p2)
TypeError: unsupported operand type(s) for +: 'Point' and 'Point'

Here, we can see that a TypeError was raised, since Python didn't know how to add two Point objects together.

However, we can achieve this task in Python through operator overloading. But first, let's get a notion about special functions.

Python Special Functions

Class functions that begin with double underscore __ are called special functions in Python.

These functions are not the typical functions that we define for a class. The __init__() function we defined above is one of them. It gets called every time we create a new object of that class.

Using special functions, we can make our class compatible with built-in functions.

>>> p1 = Point(2,3)
>>> print(p1)
<__main__.Point object at 0x00000000031F8CC0>

Suppose we want the print() function to print the coordinates of the Point object instead of what we got. We can define a __str__() method in our class that controls how the object gets printed. Let's look at how we can achieve this:

class Point:
    def __init__(self, x = 0, y = 0):
        self.x = x
        self.y = y
    
    def __str__(self):
        return "({0},{1})".format(self.x,self.y)

Now let's try the print() function again.

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "({0}, {1})".format(self.x, self.y)


p1 = Point(2, 3)
print(p1)

Output

(2, 3)

That's better. Turns out, that this same method is invoked when we use the built-in function str() or format().

>>> str(p1)
'(2,3)'

>>> format(p1)
'(2,3)'

So, when you use str(p1) or format(p1), Python internally calls the p1.__str__() method. Hence the name, special functions.

Now let's go back to operator overloading.

Overloading the + Operator

To overload the + operator, we will need to implement __add__() function in the class. With great power comes great responsibility. We can do whatever we like, inside this function. But it is more sensible to return a Point object of the coordinate sum.

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "({0},{1})".format(self.x, self.y)

    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Point(x, y)

Now let's try the addition operation again:

class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "({0},{1})".format(self.x, self.y)

    def __add__(self, other):
        x = self.x + other.x
        y = self.y + other.y
        return Point(x, y)


p1 = Point(1, 2)
p2 = Point(2, 3)

print(p1+p2)

Output

(3,5)

What actually happens is that, when you use p1 + p2, Python calls p1.__add__(p2) which in turn is Point.__add__(p1,p2). After this, the addition operation is carried out the way we specified.

Similarly, we can overload other operators as well. The special function that we need to implement is tabulated below.

Operator

Expression

Internally

Addition

p1 + p2

p1.__add__(p2)

Subtraction

p1 - p2

p1.__sub__(p2)

Multiplication

p1 * p2

p1.__mul__(p2)

Power

p1 ** p2

p1.__pow__(p2)

Division

p1 / p2

p1.__truediv__(p2)

Floor Division

p1 // p2

p1.__floordiv__(p2)

Remainder (modulo)

p1 % p2

p1.__mod__(p2)

Bitwise Left Shift

p1 << p2

p1.__lshift__(p2)

Bitwise Right Shift

p1 >> p2

p1.__rshift__(p2)

Bitwise AND

p1 & p2

p1.__and__(p2)

Bitwise OR

p1 | p2

p1.__or__(p2)

Bitwise XOR

p1 ^ p2

p1.__xor__(p2)

Bitwise NOT

~p1

p1.__invert__()

Overloading Comparison Operators

Python does not limit operator overloading to arithmetic operators only. We can overload comparison operators as well.

Suppose we wanted to implement the less than symbol < symbol in our Point class.

Let us compare the magnitude of these points from the origin and return the result for this purpose. It can be implemented as follows.

# overloading the less than operator
class Point:
    def __init__(self, x=0, y=0):
        self.x = x
        self.y = y

    def __str__(self):
        return "({0},{1})".format(self.x, self.y)

    def __lt__(self, other):
        self_mag = (self.x ** 2) + (self.y ** 2)
        other_mag = (other.x ** 2) + (other.y ** 2)
        return self_mag < other_mag

p1 = Point(1,1)
p2 = Point(-2,-3)
p3 = Point(1,-1)

# use less than
print(p1<p2)
print(p2<p3)
print(p1<p3)

Output

True
False
False

Similarly, the special functions that we need to implement, to overload other comparison operators are tabulated below.

Operator

Expression

Internally

Less than

p1 < p2

p1.__lt__(p2)

Less than or equal to

p1 <= p2

p1.__le__(p2)

Equal to

p1 == p2

p1.__eq__(p2)

Not equal to

p1 != p2

p1.__ne__(p2)

Greater than

p1 > p2

p1.__gt__(p2)

Greater than or equal to

p1 >= p2

p1.__ge__(p2)

There are numerous other special functions in Python. Visit to learn more about them.

Python operators
Python Special Functions