Re:Why People Should Learn Python
by squeaky-clean on Wednesday August 24, 2016 @04:11PM
(#12354864)
Nothing built in, and generally not recommended, but you can do it! If you want to be really flexible and just allow any attribute, you can do this:
class Foo:
def __init__(self, *args, **kwargs):
self.__dict__.update(**kwargs)
And it will automatically assign any keyword arguments you use as attributes to the object. For example `foo = Foo(name='Bob', age=99)`If you still want to keep a strict list of allowed attributes, you can define them as parameters, and use a shortcut to assign all local variables to attributes.
class Foo:
def __init__(self, name, age):
self.__dict__.update(locals())
del self.self
So `foo = Foo(name='Bob', age=99)` will still work as will `foo = Foo('Bob', 99)`. But `foo = Foo('Bob', 99, True)` will throw an error, as will `foo = Foo(name='Bob', age=99, likes_cake=True)`. You can add kwargs back to the parameter list if you want to allow assigning any attribute.This isn't recommended though. So for all practical purposes, Python does require a bit of boilerplate in the constructor.
Edit: Realized a cleaner way to do the second example.
Correct me if I'm wrong, but there doesn't seem to be built-in support in Python for having attributes initialized by the the constructor.
For example in Perl 6, I can write
... and I get a constructor Pair.new(x => 1, y => 42) for free, no need to write custom initializers.