__radd__可以按任何顺序使用操作数吗? [英] Can __radd__ work with the operands in any order?

查看:97
本文介绍了__radd__可以按任何顺序使用操作数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我的Fraction类在将其添加到浮点数或整数中时作为浮点数工作,这样我自然可以对其执行操作,但是仅当Fraction是最右边的操作数时,它才起作用.有没有一种方法可以使它以任何顺序与操作数一起使用,还是应该重写另一个我还没有学过的方法?

I want my Fraction class to work as a float when it's being added to floats or integers so I can naturally perform operations with it, but it's only working when the Fraction is the rightmost operand. Is there a way to make it work with the operands in any order or should I override another method that I haven't learned of?

代码(我想变量名是不言自明的):

Code (I guess variable names are pretty self-explanatory):

def __radd__(self,target):
    if type(target) == int or type(target) == float:
        return target + self.num/self.den

1 + Fraction(1,2)应当返回1.5,但Fraction(1,2) + 1会提高:

1 + Fraction(1,2) returns 1.5 as it should but Fraction(1,2) + 1 raises:

Traceback (most recent call last):
  File "/Users/mac/Desktop/programming/python/fraction.py", line 86, in <module>
    print(my_fraction + 1)
  File "/Users/mac/Desktop/programming/python/fraction.py", line 28, in __add__
    new_den = self.den * target.den
AttributeError: 'int' object has no attribute 'den'

推荐答案

__radd__特殊方法仅在您执行value + self时适用.如果要处理self + value,则需要重载 __add__特殊方法.

The __radd__ special method only applies to when you do value + self. If you want to handle self + value, you need to overload the __add__ special method.

由于它们都执行相同的操作,因此您可以执行以下操作:

Since they both do the same thing, you can just do:

def __add__(self, target):
    if isinstance(target, (int, float)):
        return target + self.num/self.den
__radd__ = __add__

记住这一点的一种简单方法是将__radd__中的r视为正确"的代表.因此,当您的班级在+运算符的右侧时,您将使用__radd__.

An easy way to remember this is to treat the r in __radd__ as standing for "right". So, you use __radd__ when your class is on the right of the + operator.

此外,您还会注意到我使用了 isinstance 进行类型检查.除了更清洁之外,大多数Python程序员更喜欢这种方式,并且

Also, you'll notice that I used isinstance to do the typechecking. Aside from being cleaner, this way is preferred by most Python programmers and is explicitly advocated in PEP 0008.

这篇关于__radd__可以按任何顺序使用操作数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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