Get int-type from 'int' string

后端 未结 4 842
Happy的楠姐
Happy的楠姐 2021-01-25 08:21

In Python, given the string\'int\', how can I get the type int? Using getattr(current_module, \'int\') doesn\'t work.

4条回答
  •  孤独总比滥情好
    2021-01-25 09:10

    With this sort of thing, if you're expecting a limited set of types, you should use a dictionary to map the names to the actual type.

    type_dict = {
       'int': int,
       'str': str,
       'list': list
    }
    
    >>> type_dict['int']('5')
    5
    

提交回复
热议问题