Inherit namedtuple from a base class in python
Asked Answered
S

2

6

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?

Spendthrift answered 23/8, 2016 at 10:19 Comment(0)
H
6

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

Heartthrob answered 23/8, 2016 at 10:42 Comment(0)
F
2

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
Former answered 30/3, 2021 at 22:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.