【问题标题】:Extending NamedTuple with Methods and Mutable Fields使用方法和可变字段扩展 NamedTuple
【发布时间】:2016-04-16 03:54:44
【问题描述】:

如何使用具有可变字段和方法的对象对 NamedTuple 进行子类化? 我的 init 采用一个模式,并且该模式的所有字段都应该是可调用的。

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

延伸:

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

我希望能够像引用 Pattern 一样引用 PatternSelection 的实例,但我也希望能够通过它的方法旋转和翻转它。

【问题讨论】:

    标签: python-3.x subclassing namedtuple


    【解决方案1】:

    我通过使用 __new__ 而不是 __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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-12
      • 2012-07-19
      • 1970-01-01
      • 2017-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多