如何使用Python创建具有属性的元组?

2024-10-01 09:26:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个class WeightedArc定义如下:

class Arc(tuple):

  @property
  def tail(self):
    return self[0]

  @property
  def head(self):
    return self[1]

  @property
  def inverted(self):
    return Arc((self.head, self.tail))

  def __eq__(self, other):
    return self.head == other.head and self.tail == other.tail

class WeightedArc(Arc):
  def __new__(cls, arc, weight):
    self.weight = weight
    return super(Arc, cls).__new__(arc)

这段代码显然行不通,因为self没有为WeightArc.__new__定义。如何将属性weight赋给WeightArc类?在


Tags: selfnewreturn定义defpropertyheadclass
2条回答

Another approach to look at the verbose option for collections.namedtuple to see an example of how to subclass tuple

更好的是,为什么不使用namedtuples我们自己呢?:)

class Arc(object):
    def inverted(self):
        d = self._asdict()
        d['head'], d['tail'] = d['tail'], d['head']
        return self.__class__(**d)

class SimpleArc(Arc, namedtuple("SimpleArc", "head tail")): pass

class WeightedArc(Arc, namedtuple("WeightedArc", "head tail weight")): pass

原始代码的修正版本是:

class WeightedArc(Arc):
    def __new__(cls, arc, weight):
        self = tuple.__new__(cls, arc)
        self.weight = weight
        return self

另一种查看详细选项的方法collections.namedtuple查看如何子类元组的示例:

^{pr2}$

{你可以从这个子类中剪切},或者粘贴它。在

要扩展此类,请在Arc中构建字段:

WeightedArc = namedtuple('WeightedArc', Arc._fields + ('weight',))

相关问题 更多 >