Dynamic Class creation with Attributes

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Dynamic Class creation with Attributes

azihsan
This post was updated on .
Hi,
that would be nice if there is a way we can create class with their minimal attributes dynamically like below

with onto:
    cls = types.new_class(cls_name, (Thing, ), kwds={'domain':Cls1, 'range':Cls/obj_1, 'namespace':...})
as of now if i want to specify the attibutes of the class i still use like below

with onto:
    cls =  types.new_class(cls_name, (Thing, ))
    cls.domain = ....
    cls.range = .....
    cls.namespace = ....
Reply | Threaded
Open this post in threaded view
|

Re: Dynamic Class creation with Attributes

franzlst
This is possible. new_class takes a further parameter called exec_body: https://docs.python.org/3/library/types.html#types.new_class

You can pass in a function that sets the required class properties:

from functools import partial

def set_class_properties(cls_dict, domain, range, namespace):
    cls_dict["domain"] = domain
    cls_dict["range"] = range
    cls_dict["namespace"] = namespace

cls =  types.new_class(cls_name, (Thing, ), None, partial(set_class_properties, domain=mydomain, range=myrange, namespace=mynamespace)