对于我的程序,我有很多地方,对象可以是字符串或包含字符串和其他类似列表的列表.这些通常是从JSON文件中读取的.他们都需要区别对待.现在,我只是使用isinstance,但这并不是最狡猾的方式,所以有没有人有更好的方法呢?
Joh*_*web 27
不需要输入模块isinstance(), str和unicode(3之前的版本-没有unicode!3)会为你做这项工作.
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(u'', (str, unicode))
True
>>> isinstance('', (str, unicode))
True
>>> isinstance([], (str, unicode))
False
>>> for value in ('snowman', u'? ', ['snowman', u'? ']):
... print type(value)
...
<type 'str'>
<type 'unicode'>
<type 'list'>
Run Code Online (Sandbox Code Playgroud)
Python 3.2 (r32:88445, May 29 2011, 08:00:24)
[GCC 4.2.1 (Apple Inc. build 5664)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance('? ', str)
True
>>> isinstance([], str)
False
>>> for value in ('snowman', '? ', ['snowman', '? ']):
... print(type(value))
...
<class 'str'>
<class 'str'>
<class 'list'>
Run Code Online (Sandbox Code Playgroud)
来自PEP008:
应始终使用对象类型比较,
isinstance()而不是直接比较类型.
由于Python3不再具有unicode或者basestring,在这种情况下(你期望列表或字符串),最好测试list
if isinstance(thing, list):
# treat as list
else:
# treat as str/unicode
Run Code Online (Sandbox Code Playgroud)
因为它兼容Python2和Python3
另一种方法,使用“请求宽恕比许可更好”的做法,在 Python 中通常首选鸭子类型,您可以尝试先做您想做的事,例如:
try:
value = v.split(',')[0]
except AttributeError: # 'list' objects have no split() method
value = v[0]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6577 次 |
| 最近记录: |