重载合理添加 [英] overloading rational add

查看:55
本文介绍了重载合理添加的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经重载了基本的加法运算符,添加了2个分数,但是现在我在添加非分数的分数时遇到了麻烦,即:3/4 + 1.


以下是我程序的一部分:

展开 | 选择 | Wrap | 行号

解决方案


我已经重载了基本的加法运算符,添加了2个分数,但是现在我在添加非分数的分数时遇到了麻烦,即:3/4 + 1。

>
这是我得到的错误:

追溯(mos最近的呼叫最后一次):

文件C:\Python25 \Rational.py,第87行,在< module>

print" a + 1:",a + 1

文件" C:\ Pithon25 \ Rational.py",第38行,在__add__

返回Rational(self .n * terms.d + terms.n * self.d,self.d * terms.d)

AttributeError:''int''对象没有属性''d''


所以,我认为我需要做的是给整个数字一个分母,这是行不通的。有谁可以带我走过这个?


谢谢!


TMS



您需要做的是检查相关参数的类型,如果它不是isinstance(arg,Rational),则添加不同的内容,或者在添加之前将其转换为Rational类型对象。前者可能是要走的路。

展开 | 选择 | Wrap | 行号


好的,很酷。我会继续努力。 TY


[font = Verdana] [size = 2]谢谢!我正在研究这个问题并且无法解决这个问题。实例的事情有所帮助,因为它阻止了它返回__init __ ..但是没有听说过实例的事情。谢谢![/尺寸] [/字体]

I have overloaded the basic addition operator, adding 2 fractions, but now I''m having trouble adding a fraction with a non fraction, ie: 3/4 + 1.

Here is part of my program:

Expand|Select|Wrap|Line Numbers

解决方案

I have overloaded the basic addition operator, adding 2 fractions, but now I''m having trouble adding a fraction with a non fraction, ie: 3/4 + 1.

This is the error I get:
Traceback (most recent call last):
File "C:\Python25\Rational.py", line 87, in <module>
print " a + 1:", a + 1
File "C:\Python25\Rational.py", line 38, in __add__
return Rational(self.n*terms.d + terms.n*self.d, self.d*terms.d)
AttributeError: ''int'' object has no attribute ''d''

So, I figured what I need to do is give the whole number a denominator, and that didn''t work. Can anyone walk me through this?

Thank you !

TMS

What you need to do is check the type of the argument in question and either add differently if it''s not isinstance(arg, Rational) or convert it to a Rational type object before you add. The former is probably the way to go.

Expand|Select|Wrap|Line Numbers


OK, cool. I will work on that. TY


[font=Verdana][size=2]THANK you! I was working on that and couldn''t figure it out. The instance thing helped because it stopped it from going back through the __init__.... Hadn''t heard of the instance thing. Thanks![/size][/font]


这篇关于重载合理添加的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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