Add to custom class in Python

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 to an internal property that I would like to increase by adding to it.

The class contains a number that refers to a location in the list. This may seem like something that can be done by a normal integer, but I need it to act as a separate type. All this is done to imitate the old gaming language. A class is its β€œvariable” class, and the value of the variable is stored in the above list. Apparently, in the older version of the game, arrays were tampered with by doing math on an instance of a variable object in order to capture another variable. Therefore, I am trying to imitate this.

+7
source share
2 answers

If you want to support adding for class instances, you need to define the __add__() method in 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 update the x attribute of MyClass instances using

 a += 3 

you can define __iadd__() .

If you want instance instances to behave as integers with some additional methods and attributes, you should just get from int .

+9
source

What you want to do is operator overload. You can do this in new python style classes by overloading the __add__ method as follows:

 >>> class Test(object): ... def __init__(self): self.prop = 3 ... def __add__(self, x): ... return self.prop + x ... >>> Test() + 4 7 >>> 
0
source

All Articles