- 熱門類別
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHPPhysics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
我們如何對具有多個運算元的 Python 運算子進行過載?
與二元運算子一樣,你可以對具有多個運算元的 Python 運算子進行過載。例如,如果你要對一個類的 + 運算子進行過載,則需要執行以下操作——
示例
class Complex(object): def __init__(self, real, imag): self.real = real self.imag = imag def __add__(self, other): real = self.real + other.real imag = self.imag + other.imag return Complex(real, imag) def display(self): print(str(self.real) + " + " + str(self.imag) + "i") a = Complex(10, 5) b = Complex(5, 10) c = Complex(2, 2) d = a + b + c d.display()
輸出
這將給出輸出——
17 + 17i
廣告