Python魔法增强任务误解 [英] Python Magic Method Augmented Assignment misunderstanding
问题描述
我创建一个简单的角度对象,它是最简单的形式,当它超过360(回0)或低于0(回到360)时重现的整数值。我实现了增强的任务的魔法方法,并且由于某种原因这不工作。
class Angle:
def __init __(self,angle):
self.angle = angle
def __add __(self,other):
检查递归,然后返回添加值。
val = self.angle + other
while val> 360:
val - = 360
while val< 0:
val + = 360
return val
def __radd __(self,other):
反映的加法。 self .__ add __(other)
def __iadd __(self,other):
增加的加法赋值。
val = self .__ add __ $ b self.angle = val
它将一个非类型的值赋给self.angle,=。它似乎应该工作,因为 self .__ add __()
返回其他添加到self.angle的值,所以为什么不会分配<$ c $
关于 __ iadd __ code>(和其他
__ iXXX __
方法):
尝试在原地进行操作(修改
self)并返回结果(可以是但不一定是
self)。
您的 __ iadd __
方法不会将非类型指派给 .angle
,它返回 None
(当函数没有显式返回时的默认值),并且将当前名称重新绑定到 None
,即:
class Foo(object):
def __init __ self,angle = 120):
self.angle = angle
def __add __(self,other):
检查递归,然后返回添加的值。
printFoo.add
val = self.angle + other
while val> 360:
val - = 360
while val< 0:
val + = 360
return val
def __iadd __(self,other):
增加的加法赋值。
printFoo.iadd
val = self .__ add __(other)
self.angle = val
f = Foo bf + = 20
print f is None
short:你想要 __ iadd __
返回有意义的,很可能 self
。
I'm creating a simple angle object which is, in it's simplest forms, an integer value that recurs when it goes above 360 (back to 0) or below 0 (back to 360). I implemented the magic methods for augmented assignment and for some reason this isn't working.
class Angle:
def __init__(self, angle):
self.angle = angle
def __add__(self, other):
"""Check for recursion, then return the added value."""
val = self.angle + other
while val > 360:
val -= 360
while val < 0:
val += 360
return val
def __radd__(self, other):
"""Reflected addition."""
return self.__add__(other)
def __iadd__(self, other):
"""Augmented addition assignment."""
val = self.__add__(other)
self.angle = val
It assigns a nonetype value to self.angle,=. It seems to me like it should work, since self.__add__()
returns the value of other added to self.angle, so why wouldn't it assign val
to self.angle?
About __iadd__
(and other __iXXX__
methods):
These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self).
Your __iadd__
method doesn't "assigns a nonetype to self.angle
", it returns None
(default value when a function has no explicit return), and this rebinds your current name to None
, ie:
class Foo(object):
def __init__(self, angle=120):
self.angle = angle
def __add__(self, other):
"""Check for recursion, then return the added value."""
print "Foo.add"
val = self.angle + other
while val > 360:
val -= 360
while val < 0:
val += 360
return val
def __iadd__(self, other):
"""Augmented addition assignment."""
print "Foo.iadd"
val = self.__add__(other)
self.angle = val
f = Foo()
f += 20
print f is None
To make a long story short : you want __iadd__
to return something meaningfull, most probably self
.
这篇关于Python魔法增强任务误解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!