I often find myself writing class constructors like this:
class foo:
def __init__(self, arg1, arg2, arg3):
self.arg1 = arg1
self.arg2 = arg2
What about iterating over the explicit variable names?
I.e.
class foo:
def __init__(self, arg1, arg2, arg3):
for arg_name in 'arg1,arg2,arg3'.split(','):
setattr(self, arg_name, locals()[arg_name])
f = foo(5,'six', 7)
Resulting with
print vars(f)
{'arg1': 5, 'arg2': 'six', 'arg3': 7}
My suggestion is similar to @peepsalot, except it's more explicit and doesn't use dir()
, which according to the documentation
its detailed behavior may change across releases