如何在Python中创建带属性的元组?

5 投票
2 回答
3338 浏览
提问于 2025-04-17 04:52

我有一个叫做 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)

这段代码显然是有问题的,因为在 WeightArc.__new__ 这个方法里,self 还没有被定义。那么,我该怎么给 WeightArc 类添加一个叫做 weight 的属性呢?

2 个回答

2

还有一种方法可以查看collections.namedtuple的详细选项,看看如何对元组进行子类化的例子。

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

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
7

你原始代码的修正版是:

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

另外一种方法是查看 collections.namedtupleverbose 选项,里面有一个关于如何继承 tuple 的例子:

>>> from collections import namedtuple, OrderedDict
>>> _property = property
>>> from operator import itemgetter as _itemgetter
>>> Arc = namedtuple('Arc', ['head', 'tail'], verbose=True)
class Arc(tuple):
    'Arc(head, tail)' 

    __slots__ = () 

    _fields = ('head', 'tail') 

    def __new__(_cls, head, tail):
        'Create new instance of Arc(head, tail)'
        return _tuple.__new__(_cls, (head, tail)) 

    @classmethod
    def _make(cls, iterable, new=tuple.__new__, len=len):
        'Make a new Arc object from a sequence or iterable'
        result = new(cls, iterable)
        if len(result) != 2:
            raise TypeError('Expected 2 arguments, got %d' % len(result))
        return result 

    def __repr__(self):
        'Return a nicely formatted representation string'
        return 'Arc(head=%r, tail=%r)' % self 

    def _asdict(self):
        'Return a new OrderedDict which maps field names to their values'
        return OrderedDict(zip(self._fields, self)) 

    def _replace(_self, **kwds):
        'Return a new Arc object replacing specified fields with new values'
        result = _self._make(map(kwds.pop, ('head', 'tail'), _self))
        if kwds:
            raise ValueError('Got unexpected field names: %r' % kwds.keys())
        return result 

    def __getnewargs__(self):
        'Return self as a plain tuple.  Used by copy and pickle.'
        return tuple(self) 

    head = _property(_itemgetter(0), doc='Alias for field number 0')
    tail = _property(_itemgetter(1), doc='Alias for field number 1')

你可以复制、粘贴并修改这段代码,或者像 namedtuple 文档 中展示的那样直接继承它。

要扩展这个类,可以基于 Arc 中的字段进行构建:

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

撰写回答