python元组的属性_我如何使用Python创建一个具有属性的元组?

原始代码的修复版本是:

class WeightedArc(Arc):

def __new__(cls, arc, weight):

self = tuple.__new__(cls, arc)

self.weight = weight

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

>>> 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 docs中所示。

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

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值