[英]check type of object given by a string in python
我想问一下如何确定python中对象的类型。 我知道该如何“正常”地进行操作,例如,
import types
def f(x):
return x
isinstance(f, types.FunctionType)
返回true。 但是,如果我只有一个包含'f'的字符串,那么说a ='f'。 我该怎么办? 我如何确定字符串指定的对象是函数还是其他? 在有人问之前,它是一个解析器,这就是为什么我不知道'f'是否是一个函数的原因;)
谢谢,
v923z
您可以在globals()
(全局符号表和locals()
(本地符号表))中查找名称:
Python 2.6.1 (r261:67515, Jun 24 2010, 21:47:49)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> def f(x):
... return x
...
>>> globals()['f']
<function f at 0x1004c0230>
>>> import types
>>> isinstance(globals()['f'], types.FunctionType)
True
>>>
要了解其类型,可以从字符串到其实际表示形式进行评估:
def f(x):
return x
a = "f"
aEvaluated = eval(a)
print(type(aEvaluated))
isinstance(aEvaluated, types.FunctionType)
如果“ f”是指本地环境中的变量,则可以使用globals()查找它:
>>> def f(x):
return x
>>> a = 'f'
>>> type(globals()[a])
<type 'function'>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.