4 ms·
The second annoyance is that you need to write __init__ methods quite often. Correct me if I'm wrong, but there doesn't seem to be built-in support in Python f
by perlgeek 10y ago
The second annoyance is that you need to write __init__ methods quite often.
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
class Point {
has $.x;
has $.y;
}
... and I get a constructor Pair.new(x => 1, y => 42) for free, no need to write custom initializers.
- squeaky-clean 10y agoNothing 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.