gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-30 00:46:32 25 4
gpt4 key购买 nike

我有一个类 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__ 定义。如何将属性权重分配给 WeightArc 类?

最佳答案

原始代码的修复版本是:

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

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

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

关于python - 如何使用 Python 创建具有属性的元组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7871818/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com