2017-04-10 34 views
0
class StringClass: 
    def __init__(self, str_value): 
     self.str_value = str_value 
    def __eq__(self, object): 
     if self.str_value == object.str_value: 
      return True 
     else: 
      return False 
    def __str__(self): 
     return str(self.str_value) 
    def __repr__(self): 
     return str(self.str_value) 
    def __getitem__ (self, index): 
     return self.str_value [ index ] 
    def __gt__(self, object): 
     if self.str_value > object.str_value: 
      return True 
     else: 
      return False 
class StringListClass: 
    def __init__ (self, size): 
     self.size = size # the size of the str_list 
     self.str_list = [None] * size # the list with an initial size 
     self.counter = 0 # shows which index in the list is filled 
    def add (self, new_item): 
     if self.size - 1 >= self.counter: 
      self.str_list [ self.counter ] = new_item 
      self.counter += 1 
      return print ('Element', new_item, 'has been added, the list is :', self.str_list [:self.counter]) 
     else: 
      return print ('Error! Only', self.size, 'elements can be added into the list') 

    def sort (self): 
     changed = True 
     while changed: 
      changed = False 
      for i in range (len (self) - 1): 
       if ord (self.str_list [i] [0]) > ord (self.str_list [i + 1] [0]): 
        self.str_list [i], self.str_list [i + 1] = self.str_list [i + 1], self.str_list [i] 
        changed = True 
     return print ('Sorted list:', self.str_list [:len (self)]) 
    def search (self, target_item): 
     self.sort () 
     low = 0 
     high = len (self) - 1 
     while low <= high: 
      mid = (low + high) // 2 
      if self.str_list [mid] == target_item: 
       return print ('The element', target_item, 'has been found!') 
      elif target_item < self.str_list [mid]: 
       high = mid - 1 
      else: 
       low = mid + 1 
     return print ('The element ', target_item, 'is not listed in the list!') 
    def __len__ (self): 
     return self.counter 

    def __str__ (self): 
     string = "" 
     if len (self) != 0: 
      for i in range (len (self)): 
       string += str (i) + ' element is: ' + str (self.str_list [i]) + "\n" 
     else: 
      string = "The list is empty!" 
     return string 



list = StringListClass (10) 
a = StringClass ('Hello') 
b = StringClass ('how') 
c = StringClass ('are') 
d = StringClass ('you') 
list.add (a) 
list.add (b) 
list.add (c) 
list.add (d) 
list.sort() 
list.search('how') 

的list.search( '如何')返回AttributeError的:__eq__重載方法不能正常工作


AttributeError       Traceback (most recent call last) 
<ipython-input-40-49ee6e8bf4c7> in <module>() 
    104 
    105 list.sort() 
--> 106 list.search('how') 
    107 
    108 print(a) 

<ipython-input-40-49ee6e8bf4c7> in search(self, target_item) 
    67    mid = (low + high) // 2 
    68 
---> 69    if self.str_list [mid] == target_item: 
    70     return print ('The element', target_item, 'has been found!') 
    71    elif target_item < self.str_list [mid]: 

<ipython-input-40-49ee6e8bf4c7> in __eq__(self, object) 
     7  def __eq__(self, object): 
     8 
----> 9   if self.str_value == object.str_value: 
    10    return True 
    11   else: 

AttributeError: 'str' object has no attribute 'str_value' 

你能解釋一下,請,什麼是錯在__ __均衡方法在StringClass中?

+1

您創建了一個'StringClass'實例列表,但是您搜索了一個'str'。 (爲什麼你甚至沒有任何這些類?) – user2357112

+2

錯誤信息實際上是相當具有描述性的:你用''how'''調用搜索,這是'str'。字符串沒有'.str_value'屬性(你的字符串類有),你的'.__ eq __()'試圖訪問它。 – dhke

回答

1

您需要比較兩個相同類型的項目。您嘗試比較StringClass和內置str。當python嘗試讀取內置字符串的屬性str_value(這是它不具有的屬性)時,會發生失敗點。

而是將StringClass轉換爲search函數。

list.search(StringClass('how')) 

或執行內部search該轉換,雖然這則意味着不能傳遞StringClass到函數。

另外,您不應該調用任何變量list。這是一種內置類型,在聲明之後,您隱藏了內置版本list

+0

是否有可能在類StringClass的__eq__方法中執行轉換? –

+0

無論你喜歡什麼,你都可以做到。雖然這不會讓我成爲一個好地方。主要是因爲它限制了'__eq__'函數的允許輸入並改變它的語義。任何使用它的人都希望'__eq__'比較像'StringClass'的'StringClass'。如果突然它必須是左邊的'StringClass'和右邊的'str',那麼當你忘記這個區別時,你可能會在後面遇到一些神祕的錯誤。 –