__eq__重载方法无法正常工作

时间:2017-04-10 05:06:03

标签: python python-3.x

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('how')返回AttributeError:

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中的__ eq __方法有什么问题?

1 个答案:

答案 0 :(得分:1)

您需要比较两个相同类型的项目。您尝试比较StringClass和内置str。当python尝试读取内置字符串的属性str_value时会发生故障点,这是一个它没有的属性。

而是将StringClass传递给search函数。

list.search(StringClass('how'))

或在search内执行转换,但这意味着您无法将StringClass传递给该函数。

顺便说一句,你不应该调用任何变量list。它是内置类型,在声明之后,您隐藏内置版本的list