Skip to main content
 首页 » 编程设计

python之从python中的基类继承namedtuple

2024年10月17日7www_RR

是否可以生成一个继承自基类的namedtuple?

我想要的是 Circle 和 Rectangle 是 namedtuple 并且继承自一个公共(public)基类('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 

(您应该考虑将 __slots__ 添加到所有三个类中以节省内存并加快查找速度。)