使用字符串访问内置 class
Accessing a built-in class with a string
我想使用字符串从 Python 中检索内置 class。通过trial/error,我找到了实现的方法:
>>> __builtins__.__dict__['str']
<class 'str'>
>>> __builtins__.__dict__['int']
<class 'int'>
是否有更 Pythonic 的方法来做到这一点?有更安全的方法吗?
最好通过 vars()
完成,而不是抢模块 __dict__
。抢钱通常不是最好的主意,因为它们可能会发生变化;这就是像 vars
这样的内置函数存在的原因;它会获取您提供的对象的字典,
所以,而不是:
>>> __builtins__.__dict__['str']
使用:
>>> vars(__builtins__)['str']
具有相同的效果,同时也更安全且更具可读性。
您可以使用 Python 的内置 eval()
函数,这将避免引用任何带有双下划线名称的内容(并且是安全的,因为该字符串来自受信任的来源):
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
current directory: "C:\vols\Files\PythonLib\Stack Overflow"
>>> eval('str')
<class 'str'>
>>> eval('int')
<class 'int'>
我想使用字符串从 Python 中检索内置 class。通过trial/error,我找到了实现的方法:
>>> __builtins__.__dict__['str']
<class 'str'>
>>> __builtins__.__dict__['int']
<class 'int'>
是否有更 Pythonic 的方法来做到这一点?有更安全的方法吗?
最好通过 vars()
完成,而不是抢模块 __dict__
。抢钱通常不是最好的主意,因为它们可能会发生变化;这就是像 vars
这样的内置函数存在的原因;它会获取您提供的对象的字典,
所以,而不是:
>>> __builtins__.__dict__['str']
使用:
>>> vars(__builtins__)['str']
具有相同的效果,同时也更安全且更具可读性。
您可以使用 Python 的内置 eval()
函数,这将避免引用任何带有双下划线名称的内容(并且是安全的,因为该字符串来自受信任的来源):
Python 3.5.2 (v3.5.2:4def2a2901a5, Jun 25 2016, 22:01:18) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
current directory: "C:\vols\Files\PythonLib\Stack Overflow"
>>> eval('str')
<class 'str'>
>>> eval('int')
<class 'int'>