在Python中添加到自定义类 [英] Add to custom class in Python

查看:160
本文介绍了在Python中添加到自定义类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够以以下样式添加到自定义类:

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

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

7当然对应于一个内部属性我想通过添加来增加它。

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.

推荐答案

如果要支持类实例的加法,则需要定义一个<类上的href = http://docs.python.org/reference/datamodel.html#object.__add__> __ add __() 方法:

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

示例:

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

还要支持 3 + a ,定义 __ radd __() 方法。

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

如果您希望能够更新<$ c的 x 属性$ c> MyClass 实例,使用

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

a += 3

您可以定义 __ iadd __()

you can define __iadd__().

如果您希望类实例的行为类似于带有某些其他方法和属性的整数,您应该只从 int 得出。

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

这篇关于在Python中添加到自定义类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆