Inherit namedtuple from a base class in python

2019-02-19 18:04发布

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条回答
The star\"
2楼-- · 2019-02-19 18:55

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.)

查看更多
登录 后发表回答