1

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?

1 Answer 1

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Interesting, I was making it to look like an int, with +, and you are making it to look like WorldTile.
This is the correct way for classes which should model their behaviour after immutable builtins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.