python方法使用附加数据生成整数类

时间:2014-01-14 13:51:13

标签: python class

美好的一天! 我想在python中的类来存储里面的地图图块,比如

map = [[WorldTile() for _ in range(10)] for _ in range(10)]

我创建了课程

class WorldTile:
    def __init__(self, val):
        self.resource = val
        self.objects = dict()

    def __repr__(self):
        return self.resource

    def __str__(self):
        return '%s' % (str(self.resource))

    def __cmp__(self, other):
        return cmp(self.resource, other)

    def __add__(self, other):
        self.resource += other
        return self.resource

    def __sub__(self, other):
        self.resource -= other
        return self.resource

但出了点问题。 我试试

x = WorldTile.WorldTile(7)
print type(x), id(x), x
print x > 2, x < 5, x > 0
#x += 5
print type(x), id(x), x
print x, str(x), type(x)
print x.objects

他们工作正常,但如果我取消注释行x += 5 x成为<type 'int'>

完全,我想要上课,我可以作为整数(x = x +-*\ y等),但也可以在必要时访问其他字段(x.objects) 我想我需要覆盖assignemet方法,但这在python中是不可能的。还有其他办法吗?

1 个答案:

答案 0 :(得分:2)

您可以覆盖__iadd__的{​​{1}}。

但是,您当前的+=已被破坏。您可以通过返回__add__的(新)实例而不是WorldTile来修复它:

int

这适用于def __add__(self, other): return WorldTile(self.resource + other) +(处理+=留给读者练习。)