python - 在 Python 中从字符串中获取类型实例

标签 python

因此,我需要将值转换为给定类型:

if 'int' == type_name:
    value = int(value)
elif 'str' == type_name:
    value = str(value)
...

有没有办法通用地做到这一点?例如:

type_instance = get_type_instance(type_name)
value = type_instance(value)

我正在使用 Python 2.7,但也对 Python 3.X 解决方案感兴趣。

更新:

这是我正在使用的解决方案:

class Token:

    def __init__(self, type_name, value):
        self.type = type_name
        self.value = __builtins__[type_name](value) # not safe

这只是一个玩具解析器。 不要在生产中使用!

最佳答案

如果你只需要 __builtins__ 类型你可以做

value = getattr(__builtins__, type_name)(value)

关于python - 在 Python 中从字符串中获取类型实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12178649/

相关文章:

python - sqlalchemy.orm.exc.UnmappedInstanceError : Class 'builtins.NoneType' is not mapped

python - 如何避免在 Python 中两次查找字典以获取/设置键值?

python - 在 tf.Session() 中循环

python - 在特定列( Pandas )中首次出现 NaN 后删除所有行

python - Python 中的列表(使用 NLTK)

python - 使用 Python-xmlrpc 从外部图像链接设置 WordPress 帖子缩略图

python - 必须评估字符串才能从模块访问类

python - 在 Python 中使用 numpy/scipy 记录非常小的值

python - 在 Ubuntu 中为 weasyprint 安装最新的 cairo lib

python - 有什么方法可以在不中断程序的情况下检查 Python 脚本的进度?