3 ms·
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
by squeaky-clean 10y ago
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.
- amyjess 10y agoI believe you could also accomplish this with a metaclass, as well.