On 15 April 2016 at 10:48, Albert-Jan Roskam <sjeik_ap...@hotmail.com> wrote: > What I like about both namedtuple and AttrDict is attribute lookup: that > makes code so, so, soooo much easier to read. This seems to be a nice > generalization of your code: > > class Point(object): > > def __init__(self, **kwargs): > Point.__slots__ = kwargs.keys() > for k, v in kwargs.items(): > setattr(self, k, v)
This is not how __slots__ is supposed to work. __slots__ should be defined in the class statement (outside of any method). The way that __slots__ works is kind of magical so you can't just set the attribute on the class any time you like. I was just imagining that you would define a class with __slots__ listing the attributes instances should have when you want one. That's how namedtuple works: you make a class with particular attributes. You seem to want to generalise that so that each instance has different attributes which is not really the idea. If you just want an object to which you can attach some attributes then I think you want types.SimpleNamespace: https://docs.python.org/3/library/types.html#additional-utility-classes-and-functions That's new in 3.4 but the docs show how to make something similar: class SimpleNamespace: def __init__(self, **kwargs): self.__dict__.update(kwargs) def __repr__(self): keys = sorted(self.__dict__) items = ("{}={!r}".format(k, self.__dict__[k]) for k in keys) return "{}({})".format(type(self).__name__, ", ".join(items)) def __eq__(self, other): return self.__dict__ == other.__dict__ Notice that it just passes the kwargs through to __dict__ rather than subclassing __dict__ and using a self-reference. -- Oscar _______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor