dynamic class creation in python -
i want create class dynamically:
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)))
i went through many links find resources dynamic class creation of classes basic variables declarations , function.
class foo(object): x = 10 y = 20 def get_x(self): return self.x def get_y(self): return self.y
dynamic class creation can done as:
bar = type( 'bar', (object,), dict( x = 10, y = 20, get_x=lambda self:self.x, get_y=lambda self:self.y ) )
but don't know how crete createaent class , define functions dynamically..
this code have written:
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
it gives me following error:
typeerror: metaclass conflict: metaclass of derived class must (non-strict) subclass of metaclasses of bases
i don't know how define get_parser function.
ps: hints helpful
in type()
command have (object,),
want have
(show.showone, object),
and have dict(...)
existing dictionary:
def some_func(self): do_something() cls_dict['some_func'] = some_func
and bar
creation like:
# towards top of file import show # somewhere else in file... bar = type( 'bar', (show.showone, object), cls_dict, )
Comments
Post a Comment