在 Python 中遇到意外的类行为

我运行了下面的代码;


class A:

    def __init__(self):

        self.f = 1


    def __add__(self, x):

        self.f += x

        return self


    def __radd__(self, x):

        self.f += x

        return self

>>> a = A()

>>> a + 2

<__main__.A object at 0x7f96a90d5700>

>>> a.f == 3

True


# as expected, so far


>>> a = A()

>>> b = A()

>>> a + b

<__main__.A object at 0x7f3d86d7c700>


>>> a.f

<__main__.A object at 0x7f3d86d7cb80>

>>> b.f

2

>>> a.f.f

2

>>> a.f is b

True

刚才发生了什么?为什么是a.f == b和b.f == 2。


我想知道这是否是某种明确的行为,我没有正确解释。


慕村9548890
浏览 118回答 1
1回答

犯罪嫌疑人X

该线路在 上a + b呼叫__add__接线员a。+=不起作用 ( ) 并因此int + A调用__radd__on&nbsp;b。在这里,b.f接收值2并将自身作为对象返回。然后将此对象分配给a.f.所以一切都符合预期,除了非常不寻常的编码方式。我希望您编写的代码不会伤害到任何人。即使您坚持自己的编码,让我(至少对于其他读者)建议定义这些运算符的正常方法:def __add__(self, x):&nbsp; &nbsp; result = A()&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; result.f = self.f + x.f&nbsp; &nbsp; except AttributeError:&nbsp; &nbsp; &nbsp; &nbsp; result.f = self.f + x&nbsp; &nbsp; return resultdef __radd__(self, x):&nbsp; &nbsp; result = A()&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; result.f = self.f + x.f&nbsp; &nbsp; except AttributeError:&nbsp; &nbsp; &nbsp; &nbsp; result.f = self.f + x&nbsp; &nbsp; return result现在你可以计算a+b,2+a等等a+2。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python