I want to create this class by 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 but could find resources for dynamic class creation of classes with basic variables declarations and 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 be done as:
Bar = type(
'Bar',
(object,),
dict(
x = 10,
y = 20,
get_x=lambda self:self.x,
get_y=lambda self:self.y
)
)
But i don't know how to crete CreateAent class and define its functions dynamically..
This is the code that i 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 the following error:
TypeError: metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases
I don't know how to define get_parser function.
PS: Some hints will be really helpful
CreateAgentMakerfunction that returned a new class with your attributes. You can even use@classmethodto do it asCreateAgent.dynamic_from_string("name",(parents,), {"key":"value", "attri":"butes"})