Search code examples
python-3.xsubclassingnamedtuple

Extending NamedTuple with Methods and Mutable Fields


How can I subclass NamedTuple with an object that has mutable fields and methods? My init takes a pattern and all the fields of the pattern should be callable.

class PatternSelection(Patterns.Pattern):
    def __init__(self, pattern):
        self.xflipped=False
        self.yflipped=False
        self.rotation=0

    def horizontal_flip(self):
        if self.rotation%2==0:
            self.xflipped^=True
        else:
            self.yflipped^=True

    def vertical_flip(self):
        if self.rotation%2==0:
            self.yflipped^=True
        else:
            self.xflipped^=True

    def rotate_pattern(self):
        self.rotation=(self.rotation+1)%4

Which extends:

Pattern=namedtuple('Patterns', 'width height rules commands')

I want to be able to refer to an instance of PatternSelection as if it were a Pattern, but I also want to be able to rotate and flip it through it's methods.


Solution

  • I solved it by using __new__ instead of __init__:

    def __new__(cls, pattern):
        new_selection = super().__new__(cls, *pattern)
        new_selection.xflipped = False
        new_selection.yflipped = False
        new_selection.rotation = 0
        return new_selection