Reputation: 13
Good day! I'm think about class in python to store a map tiles inside, such as
map = [[WorldTile() for _ in range(10)] for _ in range(10)]
i create class
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
but something going wrong. i'l try
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
they work fine, but if i'l uncomment line x += 5
x becoming an <type 'int'>
totally, i'm want to have class, with i can work as integer ( x = x +-*\ y
etc ), but also can access additional fields if necessary ( x.objects
)
i think i need override assignemet method, but that not possible in python. Any other way for me?
Upvotes: 1
Views: 76
Reputation: 500377
You could override __iadd__
for +=
.
However, your current __add__
is broken. You could fix it by making it return a (new) instance of WorldTile
rather than an int
:
def __add__(self, other):
return WorldTile(self.resource + other)
This will work for both +
and +=
(handling self.objects
is left as an exercise for the reader).
Upvotes: 2