質問編集履歴
1
加算以外の減算・乗算・除算への応用
title
CHANGED
File without changes
|
body
CHANGED
@@ -71,5 +71,79 @@
|
|
71
71
|
instance
|
72
72
|
となっています
|
73
73
|
|
74
|
+
|
75
|
+
##追記
|
76
|
+
無事、加算については解決いたしました。ありがとうございました。
|
77
|
+
|
78
|
+
追加の質問なのですが、減算、乗算については同様に行えたのですが、除算が以下のようになってしまいます。解決方法がございましたら、教えていただけると幸いです。
|
79
|
+
|
80
|
+
### 発生している問題・エラーメッセージ(追記)
|
81
|
+
|
82
|
+
```
|
83
|
+
2 / one_half
|
84
|
+
---------------------------------------------------------------------------
|
85
|
+
RuntimeError Traceback (most recent call last)
|
86
|
+
<ipython-input-47-5bb4201c0f77> in <module>()
|
87
|
+
----> 1 2 / one_half
|
88
|
+
|
89
|
+
47
|
90
|
+
48 def __rdiv__(self,other):
|
91
|
+
---> 49 return 1 / (self / other)
|
92
|
+
RuntimeError: maximum recursion depth exceeded while calling a Python object
|
93
|
+
```
|
94
|
+
### 該当のソースコード(追記)
|
95
|
+
|
96
|
+
```python
|
97
|
+
class Rat:
|
98
|
+
n = 0
|
99
|
+
d = 0
|
100
|
+
|
101
|
+
def __init__(self, n, d=1):
|
102
|
+
self.n = n
|
103
|
+
self.d = d
|
104
|
+
|
105
|
+
def __repr__(self):
|
106
|
+
return '{}/{}'.format(self.n, self.d)
|
107
|
+
|
108
|
+
def __add__(self,other):
|
109
|
+
if isinstance(other,Rat) == False:
|
110
|
+
other= Rat(other,1)
|
111
|
+
else:
|
112
|
+
pass
|
113
|
+
return Rat((self.n * other.d) + (other.n * self.d), self.d * other.d)
|
114
|
+
|
115
|
+
def __radd__(self,other):
|
116
|
+
return self + other
|
117
|
+
|
118
|
+
def __sub__(self,other):
|
119
|
+
if isinstance(other,Rat) == False:
|
120
|
+
other= Rat(other,1)
|
121
|
+
else:
|
122
|
+
pass
|
123
|
+
return Rat((self.n * other.d) - (other.n * self.d), self.d * other.d)
|
124
|
+
|
125
|
+
def __rsub__(self,other):
|
126
|
+
return (self - other) * (-1)
|
127
|
+
|
128
|
+
def __mul__(self,other):
|
129
|
+
if isinstance(other,Rat) == False:
|
130
|
+
other= Rat(other,1)
|
131
|
+
else:
|
132
|
+
pass
|
133
|
+
return Rat(self.n * other.n, self.d * other.d)
|
134
|
+
def __rmul__(self,other):
|
135
|
+
return self * other
|
136
|
+
|
137
|
+
def __div__(self,other):
|
138
|
+
if isinstance(other,Rat) == False:
|
139
|
+
other= Rat(other,1)
|
140
|
+
else:
|
141
|
+
pass
|
142
|
+
return Rat(self.n * other.d, self.d * other.n)
|
143
|
+
|
144
|
+
def __rdiv__(self,other):
|
145
|
+
a = self / other
|
146
|
+
return 1 / a
|
147
|
+
```
|
74
148
|
### 補足情報(FW/ツールのバージョンなど)
|
75
149
|
anaconda-4.0.0
|