- 热门类别
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- 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
广告