我正在尝试__mul__在这个例子上实现
class foo:
def __init__(self, data):
self.data = data
def __mul__(self, other):
if type(other) in (int, float):
return foo(self.data * other)
else:
return foo(self.data * other.data)
if __name__ == '__main__':
f1 = foo(10)
f2 = foo(20)
(f1*f2).data # 200
(f1*50).data # 500
(50*f1).data # TypeError: unsupported operand type(s) for *: 'int' and 'instance'
Run Code Online (Sandbox Code Playgroud)
但是它在50 * f1.
有谁知道如何解决它?