Python decorator for automatic binding __init__ arguments?

code.activestate.com/recipes/551763-auto... is what you're looking for. Also see What is the best way to do automatic attribute assignment in Python, and is it a good idea?

That's it! Thank you. – André Lima Feb 20 at 22:07.

It's definitely possible, here's a somewhat naive implementation: def lazy_init(init): import inspect arg_names = inspect. Getargspec(init)0 def new_init(self, *args): for name, value in zip(arg_names1:, args): setattr(self, name, value) init(self, *args) return new_init class Person: @lazy_init def __init__(self, name, age): pass p = Person("Derp", 13) print p. Name, p.

Age Once you start having something besides attributes that map to properties, you're going to run into trouble though. You'll need at least some way to specify which args to initialize as properties... at which point it'll just become more hassle than it's worth.

Thanks. I realize that if the __init__ method is sophisticated it wouldn't be worth it, but the simple ones are so widespread that I think it would be nice to have something like that at hand. – André Lima Feb 19 at 2:26.

Here it goes, in simplest form: def lazy_init(*param_names): def ret(old_init): def __init__(self, *args, **kwargs): if len(args) > len(param_names): raise TypeError("Too many arguments") for k in kwargs: if k not in param_names: raise TypeError("Arg %r unexpected" % k) for par, arg in zip(param_names, args): setattr(self, par, arg) for par, arg in kwargs.items(): setattr(self, par, arg) old_init(*args, **kwargs) return __init__ # return ret class Q(object): @lazy_init("a", "b") def __init__(self, *args, **kwargs): print "Original init" >>> q = Q(1, 2) Original init >>> q. A, q. B (1, 2) Consider making a class decorator to cover __str__ too.

I wonder if there is something similar that people already use in such cases. Or there is any reason I'm not supposed to do it this way in the first place?

I cant really gove you an answer,but what I can give you is a way to a solution, that is you have to find the anglde that you relate to or peaks your interest. A good paper is one that people get drawn into because it reaches them ln some way.As for me WW11 to me, I think of the holocaust and the effect it had on the survivors, their families and those who stood by and did nothing until it was too late.

Related Questions