python 中重载增强算术赋值
我是 Python 新手,所以如果这是一个愚蠢的问题,请提前道歉。
对于赋值,我需要为类 myInt 重载增强算术赋值(+=、-=、/=、*=、**=、%=)。我检查了Python文档,这就是我得出的结论:
def __iadd__(self, other):
if isinstance(other, myInt):
self.a += other.a
elif type(other) == int:
self.a += other
else:
raise Exception("invalid argument")
self.a和other.a指的是存储在每个类实例中的int。我尝试按如下方式对此进行测试,但每次我得到“无”而不是预期值 5:
c = myInt(2)
b = myInt(3)
c += b
print c
任何人都可以告诉我为什么会发生这种情况吗?提前致谢。
I'm new to Python so apologies in advance if this is a stupid question.
For an assignment I need to overload augmented arithmetic assignments(+=, -=, /=, *=, **=, %=) for a class myInt. I checked the Python documentation and this is what I came up with:
def __iadd__(self, other):
if isinstance(other, myInt):
self.a += other.a
elif type(other) == int:
self.a += other
else:
raise Exception("invalid argument")
self.a and other.a refer to the int stored in each class instance. I tried testing this out as follows, but each time I get 'None' instead of the expected value 5:
c = myInt(2)
b = myInt(3)
c += b
print c
Can anyone tell me why this is happening? Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要将
return self
添加到您的方法中。说明:当
type(a)
有一个特殊方法__iadd__
时,a += b
的语义定义为:所以 if < code>__iadd__ 返回与
self
不同的内容,这就是操作后将绑定到名称a
的内容。由于缺少return
语句,您发布的方法相当于return None
的方法。You need to add
return self
to your method. Explanation:The semantics of
a += b
, whentype(a)
has a special method__iadd__
, are defined to be:so if
__iadd__
returns something different thanself
, that's what will be bound to namea
after the operation. By missing areturn
statement, the method you posted is equivalent to one withreturn None
.Python 中的增强运算符必须返回要分配给它们被调用的名称的最终值,通常(在您的情况下)
self
。与所有 Python 方法一样,缺少 return 语句意味着返回None
。另外,
Exception
,这是不可能被理智地捕获的。执行此操作的代码必须为except Exception
,它将捕获所有 异常。在这种情况下,您需要ValueError
或TypeError
。type(foo) == SomeType
进行类型检查。在这种(以及几乎所有)情况下,isinstance
效果更好,或者至少是相同的。myInt
)时,都应该使用大写字母命名它,以便人们可以将其识别为类名。Augmented operators in Python have to return the final value to be assigned to the name they are called on, usually (and in your case)
self
. Like all Python methods, missing a return statement implies returningNone
.Also,
Exception
, which is impossible to catch sanely. The code to do so would have to sayexcept Exception
, which will catch all exceptions. In this case you wantValueError
orTypeError
.type(foo) == SomeType
. In this (and virtually all) cases,isinstance
works better or at least the same.myInt
, you should name it with capital letters so people can recognize it as a class name.是的,你需要“返回自我”,它看起来像这样:
Yes, you need "return self", it will look like this: