本文介绍了从python中的基类继承namedtuple的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以生成一个继承自基类的 namedtuple
?
Is it possible to produce a namedtuple
which inherits from a base class?
我想要的是 Circle
和 Rectangle
是 namedtuple
s并且继承自公共基类('Shape'):
What I want is that Circle
and Rectangle
are namedtuple
s 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')
我该怎么做?
推荐答案
你可以试试这个:
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.)
这篇关于从python中的基类继承namedtuple的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!