Python运算符重载用法实例

yipeiwu_com6年前Python基础

本文实例讲述了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程序设计有所帮助。

相关文章

python实现停车管理系统

Python停车管理系统可实现车辆入库,按车牌号或者车型查询车辆,修改车辆信息,车辆出库时实现计费,按车型统计车辆数和显示全部车辆信息的功能 (1)定义车辆类,属性有车牌号、颜色、车型(...

Python中的包和模块实例

一、实例和结果 1)实例的结构和具体的文件: 复制代码 代码如下: PyPackage │  PyCommonM.py │  __init__.py │ ├─p1Pa...

Python BeautifulSoup [解决方法] TypeError: list indices must be integers or slices, not str

在python的Beautiful Soup 4 扩展库的使用过程中出现了 TypeError: list indices must be integers or slices, no...

python实现通过shelve修改对象实例

本文实例讲述了python实现通过shelve修改对象的方法,分享给大家供大家参考。 具体实现方法如下: import shelve she = shelve.open('try.s...

python3实现ftp服务功能(客户端)

python3实现ftp服务功能(客户端)

本文实例为大家分享了python3实现ftp服务功能的具体代码,供大家参考,具体内容如下 客户端 main代码: #Author by Andy #_*_ coding:utf-8...