python找不到自定义类,在Python中添加到自定义类

"本文介绍如何在Python中为自定义类实现加法操作,通过定义`__add__()`和`__radd__()`方法使类实例能够进行加法运算,并更新实例属性。示例展示了如何创建一个类,使得`x=myclass("Something", 7)`这样的实例可以进行类似`x+37`的操作,从而模仿旧游戏语言中的变量行为。"
摘要由CSDN通过智能技术生成

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值