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

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

问题描述

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

x=myclass("某事", 7)× + 3

当然,7 对应于我想通过添加来增加的内部属性.

该类包含一个数字,该数字引用列表中的某个位置.这看起来像是可以通过普通整数完成的事情,但我需要它作为一个单独的类型.这一切都是为了模仿一种旧的游戏语言.该类是它的变量"类,变量的值存储在上述列表中.显然,在旧版本的游戏中,通过对变量对象实例进行数学运算来获取不同的变量来伪造数组.所以我正在努力模仿.

解决方案

如果你想支持类实例的添加,你需要定义一个 __add__() 类上的方法:

class MyClass(object):def __init__(self, x):自我.x = xdef __add__(self, other):返回 self.x + 其他

示例:

<预><代码>>>>a = MyClass(7)>>>一个 + 310

要同时支持 3 + a,请定义 __radd__() 方法.

如果您希望能够使用

更新MyClass实例的x属性

a += 3

您可以定义__iadd__().

如果您希望类实例的行为类似于带有一些附加方法和属性的整数,您应该简单地从 int 派生.

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.

解决方案

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.

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

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