Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.7k users

...