我见过很多次类似的东西:
def parse(text):
if hasattr(text, 'read'):
text = text.read()
# Parse the text here...
但是如果我传递下面类的一个实例,它肯定会失败:
class X(object):
def __init__(self):
self.read = 10
我的问题是:什么是处理它的最pythonic 方式?
我一直在思考两种主要方式:
if hasattr(text, 'read') and callable(text.read):
text = text.read()
和
try:
text = text.read()
except ...
请您参考如下方法:
pythonic 方法是假设text是适合的任何类型。仅使用 try-except/hasattr如果你知道 text在不同的时间会是完全不同的东西
换句话说,不验证。仅使用 if如果你要去 else , 和 try如果你真的想在 except 中进行特殊处理.
