将字符串转换为 Python 类对象? [英] Convert string to Python class object?
本文介绍了将字符串转换为 Python 类对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个字符串作为 Python 函数的用户输入,如果当前定义的命名空间中有一个具有该名称的类,我想从中获取一个类对象.本质上,我想要一个会产生这种结果的函数的实现:
Foo 类:经过str_to_class("Foo")==><class __main__.Foo at 0x69ba0>
这可能吗?
解决方案
警告:
eval()
可用于执行任意 Python 代码.您应该永远将eval()
用于不受信任的字符串.(请参阅Python 的 eval() 在不受信任的字符串上的安全性?)
这看起来最简单.
<预><代码>>>>类 Foo(对象):... 经过...>>>评估(富")<class '__main__.Foo'>Given a string as user input to a Python function, I'd like to get a class object out of it if there's a class with that name in the currently defined namespace. Essentially, I want the implementation for a function which will produce this kind of result:
class Foo:
pass
str_to_class("Foo")
==> <class __main__.Foo at 0x69ba0>
Is this, at all, possible?
解决方案
Warning:
eval()
can be used to execute arbitrary Python code. You should never useeval()
with untrusted strings. (See Security of Python's eval() on untrusted strings?)
This seems simplest.
>>> class Foo(object):
... pass
...
>>> eval("Foo")
<class '__main__.Foo'>
这篇关于将字符串转换为 Python 类对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文