Home  >  Article  >  Backend Development  >  Python运算符重载用法实例

Python运算符重载用法实例

WBOY
WBOYOriginal
2016-06-10 15:11:191404browse

本文实例讲述了Python运算符重载用法。分享给大家供大家参考。具体分析如下:

python中,我们在定义类的时候,可以通过实现一些函数来实现重载运算符。

例子如下:

# -*- coding:utf-8 -*- 
''''' 
Created on 2013-3-21 
@author: naughty 
''' 
class Test(object): 
  def __init__(self, value): 
    self.value = value 
  def __add__(self, x): 
    return self.value + x.value 
a = Test(3) 
b = Test(4) 
print a + b

运行结果为:7

上面我们重载了加法。其他类似。

希望本文所述对大家的Python程序设计有所帮助。

Statement:
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