python从字符串创建对象 [英] python create object from string

查看:270
本文介绍了python从字符串创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下一种情况。以下方法的目标是返回从传入字符串创建的对象。所以我有:

I have the next situation. The goal of the following method is to return the object created from the incoming string. So I have:

class Situation(Generator):
    pass

以及父类中的方法:

class Generator(object):
    def createsituation(self, stringsituation="situation"):
        return "Instance of Situation"

传入的字符串始终等于字符串 situation。

The incoming string always equals to string "situation". Is it possible in python?

推荐答案

您可以轻松地将字符串映射到类,是的。类只是更多的对象,您可以将它们存储在其他Python对象中。

You can easily map strings to classes, yes. Classes are just more objects, you can store them in other Python objects.

您可以手动构建将字符串映射到类的字典:

You can manually build a dictionary mapping strings to classes:

classes = {'situation': Situation}

您可以通过创建类装饰器来使其自动化,例如:

You can automate this a little by creating a class decorator, perhaps:

classes = {}
def register(cls):
    classes[cls.__name__.lower()] = cls
    return cls

@register
class Situation(Generator):
    # ...

每个以 @register开头的类将添加到字典中,并将类名小写为键。

Each class you prefix with @register will be added to the dictionary, with the class name lowercased as the key.

或者您可以使用 globals()函数可获得的字典模块中的所有全局变量。后者有点...过大的杀伤力,同时也存在安全隐患,您最终可能会给最终用户提供比您讨价还价更多的访问权限,因为这还会给他们提供其他您不打算公开的类和功能。

or you can use the globals() function to get a dictionary of all globals in your module. The latter is a little... overkill and also a security hazard, you could end up giving end-users way more access than you bargained for, as that also gives them other classes and functions you didn't mean to expose.

一旦您拥有一本字典,只需访问正确的课程并命名为:

Once you have a dictionary, just access the right class and call it:

class Generator(object):
    def createsituation(self, stringsituation="situation"):
        return classes[stringsituation]()

这篇关于python从字符串创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆