python 中重载增强算术赋值

发布于 2024-08-21 09:45:26 字数 514 浏览 4 评论 0原文

我是 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

呆° 2024-08-28 09:45:26

您需要将 return self 添加到您的方法中。说明:

type(a) 有一个特殊方法 __iadd__ 时,a += b 的语义定义为:

  a = a.__iadd__(b)

所以 if < code>__iadd__ 返回与 self 不同的内容,这就是操作后将绑定到名称 a 的内容。由于缺少 return 语句,您发布的方法相当于 return None 的方法。

You need to add return self to your method. Explanation:

The semantics of a += b, when type(a) has a special method __iadd__, are defined to be:

  a = a.__iadd__(b)

so if __iadd__ returns something different than self, that's what will be bound to name a after the operation. By missing a return statement, the method you posted is equivalent to one with return None.

养猫人 2024-08-28 09:45:26

Python 中的增强运算符必须返回要分配给它们被调用的名称的最终值,通常(在您的情况下)self。与所有 Python 方法一样,缺少 return 语句意味着返回 None

另外,

  • 永远不要引发Exception,这是不可能被理智地捕获的。执行此操作的代码必须为 except Exception,它将捕获所有 异常。在这种情况下,您需要 ValueErrorTypeError
  • 不要使用 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 returning None.

Also,

  • Never ever ever raise Exception, which is impossible to catch sanely. The code to do so would have to say except Exception, which will catch all exceptions. In this case you want ValueError or TypeError.
  • Don't typecheck with type(foo) == SomeType. In this (and virtually all) cases, isinstance works better or at least the same.
  • Whenever you make your own type, like myInt, you should name it with capital letters so people can recognize it as a class name.
歌入人心 2024-08-28 09:45:26

是的,你需要“返回自我”,它看起来像这样:

def __iadd__(self, other):
    if isinstance(other, myInt):
        self.a += other.a
        return self
    elif type(other) == int:
        self.a += other
        return self
    else:
        raise Exception("invalid argument")

Yes, you need "return self", it will look like this:

def __iadd__(self, other):
    if isinstance(other, myInt):
        self.a += other.a
        return self
    elif type(other) == int:
        self.a += other
        return self
    else:
        raise Exception("invalid argument")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文