【发布时间】:2015-01-12 03:30:36
【问题描述】:
在 Python 中,当实现一个序列类型时,我经常(相对而言)发现自己在编写这样的代码:
class FooSequence(collections.abc.Sequence):
# Snip other methods
def __getitem__(self, key):
if isinstance(key, int):
# Get a single item
elif isinstance(key, slice):
# Get a whole slice
else:
raise TypeError('Index must be int, not {}'.format(type(key).__name__))
代码使用isinstance() 显式检查其参数的类型。这是 Python 社区中的regarded as an antipattern。如何避免?
- 我不能使用
functools.singledispatch,因为那是quite deliberately 与方法不兼容(它将尝试在self上调度,这完全没用,因为我们已经通过OOP 多态性在self上调度)。它适用于@staticmethod,但如果我需要从self中取出东西怎么办? - 投到
int(),然后接住TypeError,检查一个分片,并可能再次加注仍然很难看,尽管可能稍微少一些。 - 将整数转换为单元素切片并使用相同的代码处理这两种情况可能更简洁,但这有其自身的问题(返回
0或[0]?)。
【问题讨论】:
-
反模式使用
type()而不是isinstance(),并在用户级别使用此类代码——在编写__dunder__方法时,您应该进行类型检查...使用@ 987654337@.
标签: python python-3.x