2012-07-02 59 views
1

我有兩個類PairSequence。一個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])) 

回答

4

下面創建你傳遞與非Pair對象列表時,Pair對象的列表,否則會Pair對象定列表簡單地分配給self.pairs

class Sequence(Pair): 
    def __init__(self, pairs): 
     if not isinstance(pairs[0], Pair): 
      self.pairs = [Pair(pos, val) for pos, val in enumerate(pairs)] 
     else: 
      self.pairs = pairs 
     self.cseg = [pair.value for pair in self.pairs] 
     self.positions = [pair.position for pair in self.pairs] 

你得到了錯誤的原因是,儘管對pairs內容您的支票,你還在其分配給self.pairs

class Sequence(Pair): 
    def __init__(self, pairs): 
     # the following code will run when you're passing a list of integers 
     if not isinstance(pairs[0], Pair): 
      self = Sequence([Pair(pos, val) for pos, val in enumerate(pairs)]) 
     # but the next line will also run 
     # which means self.pairs` is now a list of integers 
     self.pairs = pairs 
     # and that means pair in the following line is an int, not a Pair: 
     self.cseg = [pair.value for pair in pairs] 
     self.positions = [pair.position for pair in pairs] 

最後,你不應該做在一個構造以下(分配給self):

self = Sequence([Pair(pos, val) for pos, val in enumerate(pairs)]) 

你試圖「覆蓋」或「替代」的self對象,但是這意味着你要構造另一個Sequence對象在構造函數Sequence中。在這種情況下這是不必要的,因爲您可以在相同的構造函數中處理這兩種情況。這反過來又會導致更簡潔的代碼。