Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 48 additions & 31 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,81 +1,98 @@
import datetime as dt
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Беглый анализ кода.

  1. Классы желательно делить на несколько файлов (но не обязательно), у каждого должен быть свой сценарий работы, дальше с ними можно взаимодействовать при помощи импортов import.

  2. Весь код не комментирован, а если да то, не правильно почитать тут, как привольно надо https://www.python.org/dev/peps/pep-0257/

  3. Отсутствие typing тайпитингов (указателей типов), для лучшего понимания что возвращается или храниться.

  4. Нет реализации клиентской части для проверки работоспособности написанного кода

  5. Отсутствие тестов (пишутся в отдельной папке tests, с обязательным первым словом в имени файла test). "Должен быть по условию технического задания. "

from datetime import datetime as dt
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

import datetime as dt для короткого обращения к свойствам и методам библиотеки datetime изменить импорт на более уточняющий from datetime import datetime as dt



class Record:
"""- Комментарий"""
def __init__(self, amount, comment, date=''):
self.amount = amount
self.date = (
dt.datetime.now().date() if
not
date else dt.datetime.strptime(date, '%d.%m.%Y').date())
self.date = dt.now().date() if not date else dt.strptime(date, '%d.%m.%Y').date()
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Укороченный вариант передачи данных свойству, уточнением импорта импорта.
  • Удаления не нужных в данном случаи скобок.
  • За счет этих изменений, можно вывести, тернарное условие в одну строку, не превышая лимит символов.

self.comment = comment


class Calculator:
"""- Комментарий"""
def __init__(self, limit):
self.limit = limit
self.records = []

def add_record(self, record):
"""- Комментарий"""
self.records.append(record)

def get_today_stats(self):
"""- Комментарий"""
today_stats = 0
for Record in self.records:
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • В цикле for итератор не должен определяться с заглавной буквы.
  • Не должен быть назван именем класса.
  • Это имя уже зарезервировано, самим классом Record.

if Record.date == dt.datetime.now().date():
today_stats = today_stats + Record.amount

for record in self.records:
if record.date == dt.now().date():
today_stats += record.amount
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Добавление в счетчик значения можно указывать не явным оператором увеличения (сложения) +=


return today_stats

def get_week_stats(self):
"""- Комментарий"""
week_stats = 0
today = dt.datetime.now().date()
today = dt.now().date()

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

После изменения импорта, к классу .datetime можно теперь обращать более в укороченном варианте.

for record in self.records:
if (
(today - record.date).days < 7 and
(today - record.date).days >= 0
):
if 7 > (today - record.date).days >= 0:
week_stats += record.amount

return week_stats


class CaloriesCalculator(Calculator):
def get_calories_remained(self): # Получает остаток калорий на сегодня
"""- Комментарий"""
def get_calories_remained(self):
"""- Получает остаток калорий на сегодня"""
x = self.limit - self.get_today_stats()

if x > 0:
return f'Сегодня можно съесть что-нибудь' \
f' ещё, но с общей калорийностью не более {x} кКал'
return f'''
Сегодня можно съесть что-нибудь ещё,
но с общей калорийностью не более {x} кКал'''
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Строку можно прописывать в тройные кавычки.
  • Таким механизмом можно занять несколько строк, без указателей переноса на другую строку через слэш.


else:
return('Хватит есть!')
return 'Хватит есть!'
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В данном случаи кавычки указывают на, то что метод возвращает кортеж с строкой.
В примере он должен возвращать, после проверки, строку.



class CashCalculator(Calculator):
"""- Комментарий"""
USD_RATE = float(60) # Курс доллар США.
EURO_RATE = float(70) # Курс Евро.

def get_today_cash_remained(self, currency,
USD_RATE=USD_RATE, EURO_RATE=EURO_RATE):
# def get_today_cash_remained(self, currency):
def get_today_cash_remained(self, currency, usd_rate=USD_RATE, euro_rate=EURO_RATE):
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

По условию технического задания, метод et_today_cash_remained(self, usd_rate=USD_RATE, euro_rate=EURO_RATE), должен принимать единственный параметр currency.

"""- Комментарий"""
currency_type = currency
cash_remained = self.limit - self.get_today_stats()

if currency == 'usd':
cash_remained /= USD_RATE
cash_remained /= usd_rate
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Имена параметров не должны совпадать с именами аргументов класса.

currency_type = 'USD'

elif currency_type == 'eur':
cash_remained /= EURO_RATE
cash_remained /= euro_rate
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Имена параметров не должны совпадать с именами аргументов класса.

currency_type = 'Euro'

elif currency_type == 'rub':
cash_remained == 1.00
currency_type = 'руб'
cash_remained = 1.00
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

После проверки должно происходить не сравнение, а присвоение через указатель одного равно =

currency_type = 'Руб'

if cash_remained > 0:
return (
f'На сегодня осталось {round(cash_remained, 2)} '
f'{currency_type}'
)
result = round(cash_remained, 2)
return f'''
На сегодня осталось {result}
{currency_type}'''

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • Строку можно прописывать в тройные кавычки.
  • Таким механизмом можно занять несколько строк, без указателей переноса на другую строку через слэш.
  • По правилу в f-строку нельзя вносить логические операции.

elif cash_remained == 0:
return 'Денег нет, держись'
return 'Денег нет, но вы держитесь ;)'

elif cash_remained < 0:
return 'Денег нет, держись:' \
' твой долг - {0:.2f} {1}'.format(-cash_remained,
currency_type)
return f'''
Денег нет, но вы держитесь ;) :
твой долг - {-cash_remained:.2f} {currency_type}'''
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Строку можно прописывать в тройные кавычки.
Таким механизмом можно занять несколько строк, без указателей переноса на другую строку через слэш.
В данной задаче мы не используем устаревший вариант подстановки переменных через функцию str.format(), а применяем подстановку через f-строку


def get_week_stats(self):
"""- Комментарий"""
super().get_week_stats()