This is not creating new "classes" just instances of Anonyclass
.
Just as you can set instance attributes, you can set callable attributes that know to which instance they are bound.
So, assuming any callable passed as an argument will take self
as the first argument, you can change your code to:
from functools import partial
class Anonyclass(object):
def __init__(self, **kwargs):
for kwarg, attr in kwargs.items():
if callable(attr):
attr = partial(attr, self)
setattr(self, kwarg, attr)
This is needed because a callable being set in the instance bypass the mechanism Python uses to bind a method to an instance auto-adding the "self" argument to all calls. So we use functools.partial
to do the same. (It could be done with lambdas, but we'd need two levels of lambda's so that the "attr" variable would keep itself bound to the correct method, and not point to the last element assigned in the for
loop)
Also, if you want to actually create classes and not instances with attributes bound, you could just make a call to type
, passing the same arguments you get as kwargs
on your code:
def anon_class_factory(**kwargs):
return type("Anonyclass", (object,), kwargs)
This will make any function passed in kwargs
behave as a "real" method.