[Tutor] subtyping builtin type
eryksun
eryksun at gmail.com
Wed Jan 1 03:28:03 CET 2014
On Tue, Dec 31, 2013 at 7:26 PM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> from collections import namedtuple
>
> class Source(namedtuple("Source", "string i n")):
> def __new__(cls, string, i=0, n=None):
> if n is None:
> n = len(string)
> return super(Source, cls).__new__(cls, string, i, n)
namedtuple is a factory to create a tuple subclass that has properties
that use operator.itemgetter, a __dict__ property that returns a
collections.OrderedDict, plus the convenience functions _make and
_replace.
It also sets __slots__ = () to prevent instances from getting a dict.
If you subclass a 2nd time, remember to also set __slots__ = (). But
this only matters if you need better performance and smaller memory
footprint when creating thousands of instances.
More information about the Tutor
mailing list