何时应直接调用__方法__? [英] When should __method__ be called directly?

查看:101
本文介绍了何时应直接调用__方法__?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

何时应直接调用__dunder__方法?例如,代替

When should a __dunder__ method be called directly? For example, instead of

a + b

一个人可以写

a.__add__(b)

但这是个好主意吗?

推荐答案

通常,不,这不是一个好主意.毕竟,操作员在这里是有原因的,因此在可以使用操作员时,请使用它.

In general, no, it’s not a good idea. The operators are there for a reason after all, so when using the operator is possible, use it.

在某些情况下,直接调用特殊方法很有用.最常见的事情是子类化.因此,当您覆盖特殊方法并且也要调用超级方法时,您将不得不直接使用名称.

There are a few things where calling the special methods directly is useful. The most common thing would be when subclassing. So when you override a special method and you want to call the super’s method too, you will have to use the name directly.

除此之外,拥有实际方法可让您保留对其的引用,即x = a.__add__.因此,当您需要类似的东西时,可以使用它.当然,对于基本运算符也不是那么有用,因为我们有operator模块,该模块已经为运算符提供了二进制函数.

Apart from that, having actual methods allows you to keep a reference to it, i.e. x = a.__add__. So when you would need something like that, you can use it. Granted, for the base operators it’s not that useful either, as we have the operator module which gives us binary functions for the operators already.

但是可能会有一些极端情况.不过,通常来说:如果您不需要显式地 方法,请使用运算符.更清晰了.

But there might be some edge cases. In general though: If you don’t explicitely need the method, use the operator. It’s a lot clearer.

Martijn Pieters在注释中提到了另一个用例,它避免了调用反向运算符.如您所知,表达式a + b首先将尝试调用a.__add__(b).如果返回的是特殊值NotImplemented,或者换句话说,如果操作符不是通过a类型实现的,则Python将尝试调用b.__radd__(a)代替(如果b是其他类型) .因此,在要避免这种行为的情况下,可以直接调用a.__add__(b),此时您将获得一个NotImplemented值.

Martijn Pieters mentioned another use case in the comments, which is avoiding calls to the inverse operator. As you may know, an expression a + b will first try to call a.__add__(b). If that returns the special value NotImplemented though, or in other words if the operator is not implemented by the type of a, then Python will try to call b.__radd__(a) instead (if b is of a different type). So in cases where you want to avoid this behavior, you could call a.__add__(b) directly—at which point you would get a NotImplemented value though.

这篇关于何时应直接调用__方法__?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆