独自の配列クラスを作成し、imul()メソッドを実装しましたが、インスタンスで* =演算を呼び出すと、インスタンス自体がNoneTypeオブジェクトになりました。なぜそれがそのように働いたのか?Python __imul __()メソッド
class CustomArray:
def __init__(self):
self.array = []
def append(self, value):
self.array.append(value)
def __mul__(self, scaler):
return [n*scaler for n in self.array]
def __imul__(self, scaler):
#print('*= operation is called.', [n*scaler for n in self.array])
self.array = [n*scaler for n in self.array]
def __repr__(self):
return self.array.__str__()
customArray = CustomArray()
print(customArray.array)
#output:[]
customArray.append(5)
customArray.append(15)
customArray.append(25)
customArray.append(35)
customArray.append(45)
print(customArray)
#output:[5, 15, 25, 35, 45]
print(customArray*5)
#output:[25, 75, 125, 175, 225]
customArray *= 5
print(customArray)
#output:None
に動作します[これらの方法は、することができた(**( 'self'を変更する)インプレース操作を行うにしようと**結果を返す必要がありますが、 ](selfである必要はありません)。](https://docs.python.org/3/reference/datamodel.html#object.__imul__) –
スケーリングコードを複製しないようにヘルパーメソッドを作成します。 –