Классы. Калькулятор
Подскажите ,пожалуйста, как сделать так, что бы значение last записывалось в атрибут класса, а не в атрибут объекта.
class Calculator:
last = None
def __init__(self):
self.history_array = []
def sum(self, a, b):
self.history_array.append( a + b)
self.last = self.history_array[-1]
return a + b
def sub(self, a, b):
self.history_array.append( a - b)
self.last = self.history_array[-1]
return a - b
def mul(self, a, b):
self.history_array.append(a * b)
self.last = self.history_array[-1]
return a * b
def div(self, a, b, mod=False):
if mod:
self.history_array.append( a % b)
self.last = self.history_array[-1]
return a % b
else:
self.history_array.append(a / b)
self.last = self.history_array[-1]
return a / b
def history(self, n):
try:
result = self.history_array[-n]
except IndexError:
result = None
return result
def clear(self): self.last = None
Ответы (3 шт):
Перед тем, как занматься ООП советую почитать вот это: https://wombat.org.ua/AByteOfPython/object_oriented_programming.html
Так как Вы явно не до конца понимаете что такое классы и их атрибуты, поля, методы и т.д.
Выделю абзац оттуда:
Переменные, принадлежащие объекту или классу, называют полями. Объекты могут также обладать функционалом, т.е. иметь функции, принадлежащие классу. Такие функции принято называть методами класса. Эта терминология важна, так как она помогает нам отличать независимые функции и переменные от тех, что принадлежат классу или объекту. Всё вместе (поля и методы) принято называть атрибутами класса.
Пишите соответственно в поле класса, а не в поле объекта:
Calculator.last = ...
# яндекс это принял
class Calculator:
history_array = None
def __init__(self):
self.history_array = []
last_operation = None
@property
def last(self):
return Calculator.last_operation
def sum(self, a, b):
self.history_array.append('sum({}, {}) == {}'.format(a, b, a + b))
Calculator.last_operation = self.history_array[-1]
return a + b
def sub(self, a, b):
self.history_array.append('sub({}, {}) == {}'.format(a, b, a - b))
Calculator.last_operation = self.history_array[-1]
return a - b
def mul(self, a, b):
self.history_array.append('mul({}, {}) == {}'.format(a, b, a * b))
Calculator.last_operation = self.history_array[-1]
return a * b
def div(self, a, b, mod=False):
if mod:
self.history_array.append('div({}, {}) == {}'.format(a, b, a % b))
Calculator.last_operation = self.history_array[-1]
return a % b
else:
self.history_array.append('div({}, {}) == {}'.format(a, b, a / b))
Calculator.last_operation = self.history_array[-1]
return a / b
def history(self, n):
try:
result = self.history_array[-n]
except IndexError:
result = None
return result
def clear(self): Calculator.last_operation = None
from classes1_tests import Test
Test(Calculator).run_all()