-->

Inherit namedtuple from a base class in python

2019-02-19 18:31发布

问题:

Is it possible to produce a namedtuple which inherits from a base class?

What I want is that Circle and Rectangle are namedtuples and are inherited from a common base class ('Shape'):

from collections import namedtuple

class Shape:
    def addToScene(self, scene):
         ...

Circle=namedtuple('Circle', 'x y radius')
Rectangle=namedtuple('Rectangle', 'x1 y1 x2 y2')

How would I do that?

回答1:

You can try this:

class Circle(Shape, namedtuple('Circle', 'x y radius')):

    pass

(You should consider adding __slots__ to all your three classes to save memory and for sightly faster lookups.)