繁体   English   中英

从'int'字符串获取int类型

[英]Get int-type from 'int' string

在Python中,给定字符串'int' ,我如何获得int 类型 使用getattr(current_module, 'int')不起作用。

int不是您当前模块名称空间的一部分; 它是__builtins__命名空间的一部分。 因此,您将在__builtins__上运行getattr

要验证它是否是类型,您可以只检查它是否是type的实例,因为所有类型都是从它派生的。

>>> getattr(__builtins__, 'int')
<type 'int'>
>>> foo = getattr(__builtins__, 'int')
>>> isinstance(foo, type)
True

对于这种情况,如果您期望一组有限的类型,则应使用字典将名称映射到实际类型。

type_dict = {
   'int': int,
   'str': str,
   'list': list
}

>>> type_dict['int']('5')
5

尝试使用eval()

>>>eval('int')
<type 'int'>

但是请确保您对eval()给出了什么; 可能很危险。

如果您不想使用eval ,则可以存储从字符串到键入字典的映射,然后查找它:

>>> typemap = dict()
>>> for type in (int, float, complex): typemap[type.__name__] = type
...
>>> user_input = raw_input().strip()
int
>>> typemap.get(user_input)
<type 'int'>
>>> user_input = raw_input().strip()
monkey-butter
>>> typemap.get(user_input)
>>>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM