【发布时间】:2016-08-18 23:44:20
【问题描述】:
我正在尝试在此示例中实现 __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'
但是它在50 * f1 不起作用。
有人知道怎么解决吗?
【问题讨论】:
标签: python oop numpy operator-overloading