Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add to custom class in Python

Tags:

python

class

I would like to be able to add to a custom class in the style of:

x=myclass("Something", 7)
x + 3

7, of course, corresponds with an inner property that I'd like to increment by adding to it.

The class holds a number that refers to a location in a list. This might seem like something that can be done by a normal integer, but I need it to act as a separate type. This is all done to emulate an old game language. The class is its 'variable' class, and the value of the variable is stored in the aforementioned list. Apparently, on older version of the game, arrays were faked by doing math on the variable object instance to grab a different variable. So I'm trying to emulate that.

like image 783
Kelketek Avatar asked Mar 23 '12 13:03

Kelketek


1 Answers

If you want to support addition for class instances, you need to define an __add__() method on your class:

class MyClass(object):
    def __init__(self, x):
        self.x = x
    def __add__(self, other):
        return self.x + other

Example:

>>> a = MyClass(7)
>>> a + 3
10

To also support 3 + a, define the __radd__() method.

If you want to be able to update the x attribute of MyClass instances using

a += 3

you can define __iadd__().

If you want class instances to behave like integers with some additional methods and attributes, you should simply derive from int.

like image 194
Sven Marnach Avatar answered Sep 22 '22 00:09

Sven Marnach