从名称实例化 Python 类
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2226330/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Instantiate a Python class from a name
提问by klynch
So i have a set of classes and a string with one of the class names. How do I instantiate a class based on that string?
所以我有一组类和一个带有类名的字符串。如何根据该字符串实例化一个类?
class foo:
def __init__(self, left, right):
self.left = left
self.right = right
str = "foo"
x = Init(str, A, B)
I want x to be an instantiation of class foo.
我希望 x 是类 foo 的实例化。
采纳答案by Alex Martelli
If you know the namespace involved, you can use it directly -- for example, if all classes are in module zap
, the dictionary vars(zap)
is that namespace; if they're all in the current module, globals()
is probably the handiest way to get that dictionary.
如果您知道所涉及的命名空间,则可以直接使用它——例如,如果所有类都在 module 中zap
,则字典vars(zap)
就是该命名空间;如果它们都在当前模块中,globals()
则可能是获取该字典的最简便方法。
If the classes are not all in the same namespace, then building an "artificial" namespace (a dedicated dict with class names as keys and class objects as values), as @Ignacio suggests, is probably the simplest approach.
如果这些类并不都在同一个命名空间中,那么正如@Ignacio 所建议的那样,构建一个“人工”命名空间(一个专用的字典,以类名作为键和类对象作为值)可能是最简单的方法。
回答by Radagast
In your case you can use something like
在您的情况下,您可以使用类似
get_class = lambda x: globals()[x]
c = get_class("foo")
And it's even easier no get class from the module
而且更容易没有从模块中获取课程
import somemodule
getattr(somemodule, "SomeClass")
回答by Ignacio Vazquez-Abrams
classdict = {'foo': foo}
x = classdict['foo'](A, B)
回答by Mischa Arefiev
classname = "Foo"
foo = vars()[classname](Bar, 0, 4)
Or perhaps
也许
def mkinst(cls, *args, **kwargs):
try:
return globals()[cls](*args, **kwargs)
except:
raise NameError("Class %s is not defined" % cls)
x = mkinst("Foo", bar, 0, 4, disc="bust")
y = mkinst("Bar", foo, batman="robin")
Miscellaneous notes on the snippet:
关于片段的其他注释:
*args
and **kwargs
are special parameters in Python, they mean ?an array of non-keyword args? and ?a dict of keyword args? accordingly.
*args
并且**kwargs
是 Python 中的特殊参数,它们的意思是?非关键字参数数组?和?关键字参数的字典?因此。
PEP-8 (official Python style guide) recommends using cls
for class variables.
PEP-8(官方 Python 风格指南)推荐使用cls
for 类变量。
vars()
returns a dict of variables defined in the local scope.
vars()
返回在本地范围内定义的变量的字典。
globals()
returns a dict of variables currently present in the environment outside of local scope.
globals()
返回当前存在于本地范围之外的环境中的变量的字典。
回答by roma
try this
试试这个
cls = __import__('cls_name')
and this - http://effbot.org/zone/import-confusion.htmmaybe helpful
回答by Aliaksei Kuzmin
You might consider usage of metaclass as well:
您也可以考虑使用元类:
Cls = type('foo', (), foo.__dict__)
x = Cls(A, B)
Yet it creates another similar class.
然而,它创建了另一个类似的类。