1

Всем привет. Познаю Классы в python. Не могу понять реализацию метода add. Подскажите пожалуйста какая реализация более верная если между ними вообще есть разница (потому что результат выдают один и тот же)

class Example:
    def __init__(self, number):
        self.number = number

    def __add__(self, other):
        result = self.number + other.number
        # result = Example(self.number + other.number)
        return result

    def __str__(self):
        return str(self.number)

a = Example(20)
b = Example(10)
c = a + b
print(c)
4
  • print(type(c)) явно будет не один и тот же. А что правильнее — ваш личный выбор как создателя этого класса
    – andreymal
    14 окт 2020 в 11:07
  • В первом случае вы возвращаете число, а во втором объект. Напишите в методе __str__ что-то вроде return f'Example({self.number})' и увидите, в чем различие
    – EzikBro
    14 окт 2020 в 11:09
  • 2
    Насчет правильности реализации - это целиком и полностью ваш выбор, однако лично я бы ожидал, что при сложении двух объектов одного класса возвращается тоже объект этого класса, а не какое-то число.
    – EzikBro
    14 окт 2020 в 11:16
  • Спасибо ВСЕМ. Помогли
    – user404236
    14 окт 2020 в 11:31

2 ответа 2

2

Очевидно, что есть.
self.number + other.number - это число.
Example(self.number + other.number) - а это - инстанс твоего класса.

https://ideone.com/CnrZDS

class Example:
  def __init__(self, number):
    self.number = number
 
  def __add__(self, other):
    return Example(self.number + other.number)
 
  def __sub__(self, other):
    return self.number - other.number
 
  def doSmth(self):
    print(self.number)
 
a = Example(7)
b = Example(42)
 
c = a + b
d = a - b
 
c.doSmth()
d.doSmth()
49
Traceback (most recent call last):
  File "./prog.py", line 21, in <module>
AttributeError: 'int' object has no attribute 'doSmth'
2

правильно будет так:

result = Example(self.number + other.number)

потому что так в result будет объект типа Example

а так:

result = self.number + other.number 

в result будет объект типа int

пример:


a = Example(20)
b = Example(10)
c = a + b
c = c + Example(5)
print(c)

если использовать result = Example(self.number + other.number) то все будет нормально, а если result = self.number + other.number то будет ошибка:

TypeError: unsupported operand type(s) for +: 'int' and 'Example'

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.