Reputation: 3776
Is it possible to produce a namedtuple
which inherits from a base class?
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')
How would I do that?
Upvotes: 6
Views: 4682
Reputation: 305
For anyone looking for a way to implement an immutable type that derives from another type, a frozen dataclass
or attrs
might be a better option than a namedtuple
.
An example using dataclass
:
class Base:
def fun(self):
print('Base()')
@dataclass(frozen=True)
class MyType(Base):
x: int
This way, you can call fun()
on a MyType
instance:
my_type = MyType([1, 2])
my_type.fun()
But cannot assign to its members:
my_type = MyType([1, 2])
#my_type.x = [10, 20]
Note that mutable members can still be modified:
my_type = MyType([1, 2])
my_type.x[0] = 10
Upvotes: 2
Reputation: 17761
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.)
Upvotes: 6