Python运算符重载用法实例

WBOY
Release: 2016-06-10 15:11:19
Original
1504 people have browsed it

本文实例讲述了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

Copy after login

运行结果为:7

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

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

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!