我有两个班级Pair
和Sequence
. 一个Pair
对象有两个属性,位置和值。Sequence
对象是对象的序列Pair
。
class Pair():
def __init__(self, position, value):
self.position = position
self.value = value
self.pair = (position, value)
def __repr__(self):
return "< Position: {0}, Value: {1} >".format(self.position, self.value)
class Sequence(Pair):
def __init__(self, pairs):
self.pairs = pairs
self.cseg = [pair.value for pair in pairs]
self.positions = [pair.position for pair in pairs]
def __repr__(self):
return "< Seq. {0} >".format(" ".join([str(x) for x in self.cseg]))
我可以Sequence
用这个创建一个对象:
>>> Sequence([Pair(0, 2), Pair(2, 8), Pair(3, 1))
< Seq. 2 8 1 >
>>> Sequence.pairs
[< Position: 0, Value: 2 >,
< Position: 2, Value: 8 >,
< Position: 3, Value: 1 >]
如何创建一个只给出值列表的Sequence
对象,如下面的代码?Pair
在这种情况下,Pair
位置必须是从 0 到 n - 1 的序列,其中 n 是 的长度Sequence
。
>>> Sequence([2, 8, 1])
< Seq. 2 8 1 >
>>> Sequence.pairs
[< Position: 0, Value: 2 >,
< Position: 1, Value: 8 >,
< Position: 2, Value: 1 >]
我尝试使用此版本的Sequence
,但没有用。我收到了这个错误:
AttributeError: 'int' object has no attribute 'value'
class Sequence(Pair):
def __init__(self, pairs):
if not isinstance(pairs[0], Pair):
self = Sequence([Pair(pos, val) for pos, val in enumerate(pairs)])
self.pairs = pairs
self.cseg = [pair.value for pair in pairs]
self.positions = [pair.position for pair in pairs]
def __repr__(self):
return "< Seq. {0} >".format(" ".join([str(x) for x in self.cseg]))