在Python中创建我自己的“整数”对象

栏目: Python · 发布时间: 7年前

内容简介:翻译自:https://stackoverflow.com/questions/5604713/creating-my-own-integer-object-in-python

基本上我希望能够做到这样的事情:

a = Integer(1)
a += 1
print a

当然,打印第二个结果.我需要创建哪些方法才能在我的Integer类中获得此行为?

免责声明:我不打算将其用于“真实”,只是好奇.

这是一个简单而不完整的例子.查看方法__sub __,__ div__等.

class Integer(object):
    def __init__(self, val=0):
        self._val = int(val)
    def __add__(self, val):
        if isinstance(val, Integer):
            return Integer(self._val + val._val)
        return self._val + val
    def __iadd__(self, val):
        self._val += val
        return self
    def __str__(self):
        return str(self._val)
    def __repr__(self):
        return 'Integer(%s)' % self._val

然后

n = Integer()
print n
m = Integer(7)
m+=5
print m

编辑修复了__repr__并添加了__iadd__.感谢@Keith指出问题.

编辑修复__add__以允许在整数之间添加.

翻译自:https://stackoverflow.com/questions/5604713/creating-my-own-integer-object-in-python


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Practical Django Projects, Second Edition

Practical Django Projects, Second Edition

James Bennett / Apress / 2009 / 44.99

Build a django content management system, blog, and social networking site with James Bennett as he introduces version 1.1 of the popular Django framework. You’ll work through the development of ea......一起来看看 《Practical Django Projects, Second Edition》 这本书的介绍吧!

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具