Ошибки реализации метода __eq__ в структуре класса ООПPython

Программы на Python
Anonymous
Ошибки реализации метода __eq__ в структуре класса ООП

Сообщение Anonymous »

Вот пара классов

Родитель

Код: Выделить всё

class GeometricShape:
def __init__(self, name):
self.set_name(name)

def get_name(self):
return self.__name

def set_name(self,name):
validate_non_empty_string(name)
self.__name = name

def __repr__(self):
return f'GeometricShape(name={self.__name})'

def __eq__(self, other):
return(self.get_name() == other.get_name() )

Ребенок

Код: Выделить всё

class Rectangle(GeometricShape):
def __init__(self, length, width, name='Rectangle'):
#
# the parent class sets the name in the constructor
# the name is not set in the child, and we want the naming behavior
# provided by the parents constructor
super().__init__(name)
#
self.set_length(length)
self.set_width(width)

def get_length(self):
return self.__length

def get_width(self):
return self.__width

def set_length(self,length):
# Check the data
validate_positive_number(length)
self.__length = length

def set_width(self,width):
validate_positive_number(width)
self.__width  = width

def get_perimeter (self):
return 2 * self.__length + 2 * self.__width

def get_area (self):
return self.__length * self.__width

def __repr__(self):
return f'Rectangle(a={self.__length}, b={self.__width})'

# Attempted Solution 1
def __eq__(self, other):
return( (self.__width == other.get_width() ) and (self.__length == other.get_length() ))

# Attempted Solution 2
#def __eq__(self, other):
#    return( (self.__width == other.__width ) and (self.__length == other.__length ))
Я попробовал два решения для метода eq, оба по-разному терпели неудачу, приводятся соответствующие ошибки, возникающие в каждом из них.
Тесты для запуска == вызываются из зашифрованных файлов Pye.

Вот описание файлов Pye. для тех, кто спрашивал в комментариях:
Что такое py-файл в Python?

py-файлы, содержащие исходный код. Зашифрованные файлы нечитабельны и позволяют защитить авторские права разработчика. Зашифрованным файлам присваивается расширение . py и используются, если нет. py-файл доступен

Решение № 1, попробуйте eq

Код: Выделить всё

    def __eq__(self, other):
return( (self.__width == other.get_width() ) and (self.__length == other.get_length() ))

выдает следующее сообщение об ошибке:
[ОШИБКА] 2024-07-24 GMT-0500 09:38:04.607: Произошла непредвиденная ошибка.
Traceback (большинство последний вызов)
... затем длинная трассировка зашифрованных файлов, заканчивающаяся на:

geometric_shapes.py», строка 31, в eq
return(self.get_name() ==other.get_name() )

Решение № 2, попытка eq:

Код: Выделить всё

    def __eq__(self, other):
return( (self.__width == other.__width ) and (self.__length == other.__length ))

Выдает следующее сообщение об ошибке:
[ОШИБКА] 2024-07-24 GMT-0500 09:38:04.607: Произошла непредвиденная ошибка.
Traceback (большинство последний вызов)
... затем длинная трассировка зашифрованных файлов, заканчивающаяся на:

geometric_shapes.py», строка 31, в eq
return(self.get_name() ==other.get_name() )

Это мои тесты, которые, похоже, дают ожидаемые результаты:

Код: Выделить всё

geometric_shape  = GeometricShape('Triangle')
geometric_shape2 = GeometricShape('Triangle')
geometric_shape3 = GeometricShape('Square')
print(f'shape == shape2:{geometric_shape  == geometric_shape2}')
print(f'shape == shape3: {geometric_shape == geometric_shape3}')
#
rectangle = Rectangle(5, 3)
rectangle2 = Rectangle(5, 3)
rectangle3 = Rectangle(5, 4)
print(f'rectangle == rectangle2: {rectangle == rectangle2}')
print(f'rectangle == rectangle3: {rectangle == rectangle3}')
Какие продукты:

Код: Выделить всё

shape == shape2:True
shape == shape3: False
rectangle == rectangle2: True
rectangle == rectangle3: False
Для тех, кто запросил полное сообщение:

[ОШИБКА] 2024-07-24 GMT-0500 09:38:04.607: Произошла непредвиденная ошибка.
Traceback (последний вызов):
Файл "..submitter_utils\submitter.pye", строка 70, в запуске
,$ tmf-UR9QO

Код: Выделить всё

7m3:/ZUOC
Mr"HEG@322'^F
Файл ":......submitter_utils\task_handler.pye", строка 31, вgenerate_submission_archive
ONMZG-M0.d4^.q^ W*/O-kA!&&F=,HOemS^G
Файл "......submitter_utils\task_handler.pye", строка 51, в __list_files_for_submission
)QtuUN&-8jD=?N"m9rd :#TXTUSTI4'[SAo
Файл "...submitter_utils\task_handler.pye", строка 65, в generate_task_специфических_файлах
Hqt-[p'3jY=H$l-q3' VP4?99HU'p@LC(3G!
Файл "......submitter_utils\tasks.pye", строка 1040, в задаче6
+9i],]UI>>n'i1TAB&tXr; 9LBrMeSsA0Yg8
Файл "......submitter_utils\test_utils.pye", строка 329, в test_class
)JoG=k--Wumo!Ga[2H8e?[0VI'J;#Vp@Tb
Файл "......submitter_utils\test_utils.pye", строка 164, в test_methods
M?*>F'c.D4-pmO:TY>Pfa?^A%oB]KD :nJ6B
Файл "...\ppp-p4-classes-objects\geometric_shapes.py", строка 31, в eq

return(self.get_name() == Other.get_name() )
AttributeError: у объекта «NoneType» нет атрибута «get_name»

неудачные тесты вызываются из зашифрованных файлов.
Есть идеи?

Подробнее здесь: https://stackoverflow.com/questions/787 ... -structure

Вернуться в «Python»