创建我自己的“整数"Python中的对象 [英] Creating my own "integer" object in Python

查看:62
本文介绍了创建我自己的“整数"Python中的对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我希望能够执行以下操作:

Essentially I want to be able to do something like:

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

当然还有打印第二个结果.我需要创建什么方法才能在我的 Integer 类中获得这种行为?

And of course printing the number two as result. What methods do I need to create to get this behaviour in my Integer class?

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

Disclaimer: I'm not planning to use this for "real", just curious.

推荐答案

这是一个简单且不完整的示例.查看方法 __sub____div__ 等.

This is a simple and incomplete example. Look at methods __sub__, __div__ and so on.

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

EDIT 修复了 __repr__ 并添加了 __iadd__.感谢@Keith 指出问题.EDIT 修正了 __add__ 以允许整数之间的加法.

EDIT fixed __repr__ and added __iadd__. Thanks to @Keith for pointing problems out. EDIT Fixed __add__ to allow addition between Integers.

这篇关于创建我自己的“整数"Python中的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆