1
我有兩個類Pair
和Sequence
。一個Pair
對象有兩個屬性,位置和值。 A 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]))