Python 的拥趸们会说 Python 没有 switch 语句的原因是它有字典。那么,我如何使用字典来解决这个问题呢?问题在于所有值都被计算并根据输入引发异常。这只是一个存储数字或数字列表并提供乘法的类的愚蠢示例。
class MyClass(object):
def __init__(self, value):
self._value = value
def __mul__(self, other):
return {
(False, False): self._value * other._value ,
(False, True ): [self._value * o for o in other._value] ,
(True , False): [v * other._value for v in self._value] ,
(True , True ): [v * o for v, o in zip(self._value, other._value)],
}[(isinstance(self._value, (tuple, list)), isinstance(other._value, (tuple, list)))]
def __str__(self):
return repr(self._value)
__repr__ = __str__
>>> x = MyClass(2.0)
>>> y = MyClass([3.0, 4.0, 5.0])
>>> print x
2.0
>>> print y
[3.0, 4.0, 5.0]
>>> print x * y
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 8, in __mul__
TypeError: can't multiply sequence by non-int of type 'float'
我可以采用一种方法来解决这个问题,即在每个值前加上“lambda :”,并在字典查找后调用lambda函数.... "}(isinsta ...)"
是否有更好的方法?