質問するログイン新規登録

回答編集履歴

4

d

2020/05/12 14:46

投稿

tiitoi
tiitoi

スコア21962

answer CHANGED
@@ -33,6 +33,14 @@
33
33
  def __add__(self, other):
34
34
  return Hoge(self.x + other)
35
35
 
36
+ def __imul__(self, other):
37
+ self.x *= other
38
+ return self
39
+
40
+ def __iadd__(self, other):
41
+ self.x += other
42
+ return self
43
+
36
44
  def __str__(self):
37
45
  return str(self.x)
38
46
 
@@ -40,6 +48,10 @@
40
48
  x = Hoge(9)
41
49
  y = x * 2
42
50
  z = x * 2 + 2
51
+ print(y)
52
+ print(z)
53
+ x += 2
43
- print(y) # 18
54
+ print(x) # 11
55
+ x *= 2
44
- print(z) # 20
56
+ print(x) # 22
45
57
  ```

3

d

2020/05/12 14:46

投稿

tiitoi
tiitoi

スコア21962

answer CHANGED
@@ -14,4 +14,32 @@
14
14
 
15
15
  times2_plus2(Hoge(9))
16
16
  # 20
17
+ ```
18
+
19
+ ## 補足
20
+
21
+ より汎用的なクラスを設計しようと思った場合、2倍にする関数だけでなく、3倍、4倍と任意の値を乗算したい場合も出てくるかもしれないので、演算子オーバロードを使うといいかもしれません。
22
+
23
+ [Python Tips:自作クラスの演算子のふるまいを定義したい - Life with Python](https://www.lifewithpython.com/2014/06/python-redefine-operators.html)
24
+
25
+ ```python
26
+ class Hoge:
27
+ def __init__(self, x):
28
+ self.x = x
29
+
30
+ def __mul__(self, other):
31
+ return Hoge(self.x * other)
32
+
33
+ def __add__(self, other):
34
+ return Hoge(self.x + other)
35
+
36
+ def __str__(self):
37
+ return str(self.x)
38
+
39
+
40
+ x = Hoge(9)
41
+ y = x * 2
42
+ z = x * 2 + 2
43
+ print(y) # 18
44
+ print(z) # 20
17
45
  ```

2

d

2020/05/12 14:43

投稿

tiitoi
tiitoi

スコア21962

answer CHANGED
@@ -13,5 +13,5 @@
13
13
  return self.x * 2
14
14
 
15
15
  times2_plus2(Hoge(9))
16
- # 9 * 2 + 2 = 18
16
+ # 20
17
17
  ```

1

s

2020/05/12 14:38

投稿

tiitoi
tiitoi

スコア21962

answer CHANGED
@@ -1,6 +1,10 @@
1
- times2_plus2() にわたす変数の型は Hoge とし、演算は Hoge オブジェクト同士で行うようにすばどうでょうか
1
+ 自身のインスタンス変数と関係ない times2_plus2() がクラス Hoge のメソッドとして定義さているのは変な気がます
2
+ フリー関数として定義してはどうでしょうか
2
3
 
3
4
  ```python
5
+ def times2_plus2(y):
6
+ return y.times2() + 2
7
+
4
8
  class Hoge:
5
9
  def __init__(self, x):
6
10
  self.x = x
@@ -8,10 +12,6 @@
8
12
  def times2(self):
9
13
  return self.x * 2
10
14
 
11
- def times2_plus2(self, y):
12
- return y.times2() + 2
13
-
14
-
15
- Hoge(2).times2_plus2(Hoge(9))
15
+ times2_plus2(Hoge(9))
16
16
  # 9 * 2 + 2 = 18
17
17
  ```