【发布时间】:2013-03-02 08:08:11
【问题描述】:
我见过很多次这样的事情:
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 ...
【问题讨论】:
-
一般只在你无法控制是否出错时才使用
try...except。如果您可以保证通话会正常进行(就像您对callable()所做的那样,我会认为这是对try...except的不当使用。
标签: python duck-typing hasattr