python中的动态类创建

时间:2014-06-25 23:16:21

标签: python

我想动态创建这个类:

class CreateAgent(show.ShowOne):
    """Create compute agent command"""

    log = logging.getLogger(__name__ + ".CreateAgent")

    def get_parser(self, prog_name):
        parser = super(CreateAgent, self).get_parser(prog_name)
        parser.add_argument(
            "os",
            metavar="<os>",
            help="Type of OS")
        parser.add_argument(
            "architecture",
            metavar="<architecture>",
            help="Type of architecture")
        parser.add_argument(
            "version",
            metavar="<version>",
            help="Version")
        parser.add_argument(
            "url",
            metavar="<url>",
            help="URL")
        parser.add_argument(
            "md5hash",
            metavar="<md5hash>",
            help="MD5 hash")
        parser.add_argument(
            "hypervisor",
            metavar="<hypervisor>",
            help="Type of hypervisor",
            default="xen")
        return parser

    def take_action(self, parsed_args):
        self.log.debug("take_action(%s)", parsed_args)
        compute_client = self.app.client_manager.compute
        args = (
            parsed_args.os,
            parsed_args.architecture,
            parsed_args.version,
            parsed_args.url,
            parsed_args.md5hash,
            parsed_args.hypervisor
        )
        agent = compute_client.agents.create(*args)._info.copy()
        return zip(*sorted(six.iteritems(agent)))

我浏览了很多链接但是可以找到用于动态类创建具有基本变量声明和函数的类的资源。

class Foo(object):
    x = 10
    y = 20
    def get_x(self):
        return self.x
    def get_y(self):
        return self.y

动态类创建可以完成:

Bar = type(
       'Bar',
       (object,),
       dict(
            x = 10,
            y = 20,
            get_x=lambda self:self.x,
            get_y=lambda self:self.y
        ) 
       )

但我不知道如何创建CreateAent类并动态定义它的函数。

这是我写的代码:

def create_model(name, base=None, fields=None):
    model = type(name, base, fields)

    return model

if __name__ == '__main__':
    fields = {
        'os': str,
        'architecture': str,
        'version': int,
        'url': str,
        'md5hash': int,
        'hypervisor': int,
        }
    model = create_model('CreateAgent', ('Showone',), fields)
    model.os = "windows"
    print model.os
  1. 它给了我以下错误:

    TypeError:元类冲突:派生类的元类必须是其所有基础的元类的(非严格)子类

  2. 我不知道如何定义get_parser函数。

  3. PS:一些提示会非常有用

1 个答案:

答案 0 :(得分:2)

type()命令中,您希望拥有(object,),

(show.ShowOne, object),

如果你有dict(...),你也可以使用现有的词典:

def some_func(self):
    do_something()

cls_dict['some_func'] = some_func

然后您的Bar创建将如下所示:

# towards the top of your file
import show

# somewhere else in your file...
Bar = type(
        'Bar',
        (show.ShowOne, object),
        cls_dict,
        )