{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Что сегодня сделаем\n", "Библиотеку для получения курсов валют в 2 строки" ] }, { "cell_type": "code", "execution_count": 84, "metadata": {}, "outputs": [], "source": [ "from libs.exchange import Rate" ] }, { "cell_type": "code", "execution_count": 85, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "66.1854" ] }, "execution_count": 85, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Rate().usd()" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "Rate('full').AZN()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Упражнение\n", "Дана строка со значениями, которые разделены запятыми:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "line = '2019-07-01,organic,4293'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Задача**\n", "\n", "Напишите функцию column_count, которая возвращает число столбцов в такой строке\n", "\n", "**Подсказка**\n", "\n", "Можно перевести эту строку в список с помощью метода split: line.split(','). И затем посчитать количество элементов в нем (функция len)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['2019-07-01', 'organic', '4293']" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "'2019-07-01,organic,4293'.split(',')" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def column_count(line):\n", " list_line = line.split(',')\n", " return len(list_line)\n", "\n", "column_count(line)" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "def column_count(line):\n", " linestr=line.strip().split(',')\n", " lenght=len(linestr)\n", " return lenght\n", "\n", "column_count(line)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 9, "metadata": {}, "output_type": "execute_result" } ], "source": [ "line = '2019-07-01,organic,4293'\n", "\n", "def column_count(string):\n", " if string:\n", " line_list = string.strip().split(',')\n", " count = len(line_list)\n", "\n", " return count\n", " \n", " return 0\n", "\n", "column_count(line)" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "column_count('2019-07-01,organic,4293,')" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1" ] }, "execution_count": 5, "metadata": {}, "output_type": "execute_result" } ], "source": [ "column_count('2019-07-01')" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "column_count('')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Классы\n", "Пример использования переменной в разных методах" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "class AnyName:\n", " def method_1(self):\n", " self.currency = 'usd'\n", " \n", " def method_2(self):\n", " print(self.currency)" ] }, { "cell_type": "code", "execution_count": 21, "metadata": {}, "outputs": [], "source": [ "a = AnyName()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a." ] }, { "cell_type": "code", "execution_count": 22, "metadata": {}, "outputs": [ { "ename": "AttributeError", "evalue": "'AnyName' object has no attribute 'currency'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0ma\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mmethod_2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;32m\u001b[0m in \u001b[0;36mmethod_2\u001b[0;34m(self)\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mmethod_2\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 6\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mcurrency\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mAttributeError\u001b[0m: 'AnyName' object has no attribute 'currency'" ] } ], "source": [ "a.method_2()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import datetime.py" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "from datetime import datetime, timedelta" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "timedelta." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "datetime.datetime.strptime()" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "<__main__.AnyName at 0x1135fe2e8>" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [], "source": [ "a.method_1()" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'usd'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a.currency" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a.currency" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "usd\n" ] } ], "source": [ "a.method_2()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Метод __init__" ] }, { "cell_type": "code", "execution_count": 23, "metadata": {}, "outputs": [], "source": [ "# метод __init__ выполняется при вызове класса\n", "\n", "class Rate:\n", " def __init__(self):\n", " self.format = 'value'\n", " print(self.format)" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "value\n" ] } ], "source": [ "r = Rate()" ] }, { "cell_type": "code", "execution_count": 26, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'value'" ] }, "execution_count": 26, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r.format" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Класс для курсов валют" ] }, { "cell_type": "code", "execution_count": 27, "metadata": {}, "outputs": [], "source": [ "class Rate:\n", " def __init__(self):\n", " self.format = 'value'\n", " \n", " def show_current_format(self):\n", " return self.format" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "r = Rate()" ] }, { "cell_type": "code", "execution_count": 29, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'value'" ] }, "execution_count": 29, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r.show_current_format()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Пример инициализации со значением переменной" ] }, { "cell_type": "code", "execution_count": 30, "metadata": {}, "outputs": [], "source": [ "class Rate:\n", " def __init__(self, format_):\n", " self.format = format_\n", " \n", " def show_current_format(self):\n", " return self.format" ] }, { "cell_type": "code", "execution_count": 31, "metadata": {}, "outputs": [], "source": [ "r = Rate(format_='value')" ] }, { "cell_type": "code", "execution_count": 32, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'value'" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r.show_current_format()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Или сразу со значением по умолчанию" ] }, { "cell_type": "code", "execution_count": 33, "metadata": {}, "outputs": [], "source": [ "class Rate:\n", " def __init__(self, format_='value'):\n", " self.format = format_\n", " \n", " def show_current_format(self):\n", " return self.format" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'value'" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r = Rate()\n", "r.show_current_format()" ] }, { "cell_type": "code", "execution_count": 35, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'full'" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r_full = Rate(format_='full')\n", "r_full.show_current_format()" ] }, { "cell_type": "code", "execution_count": 36, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'full_123'" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# значения переменных класса можно менять\n", "\n", "r.format = 'full_123'\n", "r.show_current_format()" ] }, { "cell_type": "code", "execution_count": 37, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'full'" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r_full.format" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Упражнение\n", "Создайте класс сотрудника Employee. При инициализации класса задается имя сотрудника name и его текущая зарплата salary. Напишите следующие методы:\n", "1. Метод up, который увеличивает зарплату сотрудника на 100\n", "2. Метод print, который выводит на экран текущую зарплату сотрудника в формате \"Сотрудник Иван, зарплата 100\"" ] }, { "cell_type": "code", "execution_count": 38, "metadata": {}, "outputs": [], "source": [ "class Employee:\n", " def __init__(self, name, salary):\n", " self.name = name\n", " self.salary = salary\n", " \n", " def up(self, num=100):\n", " self.salary += num\n", " print(f'Зряплата выросла до {self.salary}') \n", " \n", " def print_(self, text=''):\n", " print(f'Сотрудник {self.name}, зарплата {self.salary}. {text}')" ] }, { "cell_type": "code", "execution_count": 39, "metadata": {}, "outputs": [], "source": [ "emp = Employee('Иван', 40)" ] }, { "cell_type": "code", "execution_count": 51, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('Иван', 640)" ] }, "execution_count": 51, "metadata": {}, "output_type": "execute_result" } ], "source": [ "emp.name, emp.salary" ] }, { "cell_type": "code", "execution_count": 56, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Сотрудник Иван, зарплата 640. \n" ] } ], "source": [ "emp.print_()" ] }, { "cell_type": "code", "execution_count": 50, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Зряплата выросла до 640\n" ] } ], "source": [ "emp.up()" ] }, { "cell_type": "code", "execution_count": 42, "metadata": {}, "outputs": [], "source": [ "elena = Employee('Елена', 200)" ] }, { "cell_type": "code", "execution_count": 55, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Зряплата выросла до 600\n" ] } ], "source": [ "elena.up()" ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "('Елена', 200)" ] }, "execution_count": 43, "metadata": {}, "output_type": "execute_result" } ], "source": [ "elena.name, elena.salary" ] }, { "cell_type": "code", "execution_count": 57, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Сотрудник Елена, зарплата 600. \n" ] } ], "source": [ "elena.print_()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class Employee:\n", " def _init_(self, name, salary):\n", " self.name = name\n", " self.salary = salary\n", " \n", " def up(self):\n", " self.salary += 100\n", " # return self.salary\n", " \n", " def print_(self):\n", " print(f'Сотрудник {self.name}, зарплата {self.salary}')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "current_salary = elena.salary" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class Employee:\n", " def __init__(name, salary):\n", " self.name = name\n", " self.salary = salary\n", " \n", " def up(self):\n", " new_salary = self.salary + 100\n", " return new_salary\n", " \n", " def print_(self):\n", " line = f\"{self.name}, зарплата {self.salary}\"\n", " return line" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Полная версия класса" ] }, { "cell_type": "code", "execution_count": 58, "metadata": {}, "outputs": [], "source": [ "import requests" ] }, { "cell_type": "code", "execution_count": 59, "metadata": {}, "outputs": [], "source": [ "class Rate:\n", " \"\"\"\n", " \n", " \"\"\"\n", " def __init__(self, format_='value'):\n", " self.format = format_\n", " \n", " def exchange_rates(self):\n", " \"\"\"\n", " Возвращает ответ сервиса с информацией о валютах в виде:\n", " \n", " {\n", " 'AMD': {\n", " 'CharCode': 'AMD',\n", " 'ID': 'R01060',\n", " 'Name': 'Армянских драмов',\n", " 'Nominal': 100,\n", " 'NumCode': '051',\n", " 'Previous': 14.103,\n", " 'Value': 14.0879\n", " },\n", " ...\n", " }\n", " \"\"\"\n", " self.r = requests.get('https://www.cbr-xml-daily.ru/daily_json.js')\n", " return self.r.json()['Valute']\n", " \n", " def make_format(self, currency):\n", " \"\"\"\n", " Возвращает информацию о валюте currency в двух вариантах:\n", " - полная информация о валюте при self.format = 'full':\n", " Rate('full').make_format('EUR')\n", " {\n", " 'CharCode': 'EUR',\n", " 'ID': 'R01239',\n", " 'Name': 'Евро',\n", " 'Nominal': 1,\n", " 'NumCode': '978',\n", " 'Previous': 79.6765,\n", " 'Value': 79.4966\n", " }\n", " \n", " Rate('value').make_format('EUR')\n", " 79.4966\n", " \"\"\"\n", " response = self.exchange_rates()\n", " \n", " if currency in response:\n", " if self.format == 'full':\n", " return response[currency]\n", " \n", " if self.format == 'value':\n", " return response[currency]['Value']\n", " \n", " return 'Error'\n", " \n", " def eur(self):\n", " \"\"\"Возвращает курс евро на сегодня в формате self.format\"\"\"\n", " return self.make_format('EUR')\n", " \n", " def usd(self):\n", " \"\"\"Возвращает курс доллара на сегодня в формате self.format\"\"\"\n", " return self.make_format('USD')\n", " \n", " def brl(self):\n", " \"\"\"Возвращает курс бразильского реала на сегодня в формате self.format\"\"\"\n", " return self.make_format('BRL')" ] }, { "cell_type": "code", "execution_count": 60, "metadata": {}, "outputs": [], "source": [ "r = Rate(format_='full')" ] }, { "cell_type": "code", "execution_count": 61, "metadata": { "scrolled": true }, "outputs": [ { "data": { "text/plain": [ "{'ID': 'R01035',\n", " 'NumCode': '826',\n", " 'CharCode': 'GBP',\n", " 'Nominal': 1,\n", " 'Name': 'Фунт стерлингов Соединенного королевства',\n", " 'Value': 85.399,\n", " 'Previous': 84.5011}" ] }, "execution_count": 61, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r.make_format('GBP')" ] }, { "cell_type": "code", "execution_count": 62, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'ID': 'R01235',\n", " 'NumCode': '840',\n", " 'CharCode': 'USD',\n", " 'Nominal': 1,\n", " 'Name': 'Доллар США',\n", " 'Value': 66.1854,\n", " 'Previous': 66.0784}" ] }, "execution_count": 62, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r.usd()" ] }, { "cell_type": "code", "execution_count": 63, "metadata": {}, "outputs": [], "source": [ "r = Rate()" ] }, { "cell_type": "code", "execution_count": 64, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'AUD': {'ID': 'R01010',\n", " 'NumCode': '036',\n", " 'CharCode': 'AUD',\n", " 'Nominal': 1,\n", " 'Name': 'Австралийский доллар',\n", " 'Value': 43.8478,\n", " 'Previous': 43.658},\n", " 'AZN': {'ID': 'R01020A',\n", " 'NumCode': '944',\n", " 'CharCode': 'AZN',\n", " 'Nominal': 1,\n", " 'Name': 'Азербайджанский манат',\n", " 'Value': 39.0129,\n", " 'Previous': 38.9498},\n", " 'GBP': {'ID': 'R01035',\n", " 'NumCode': '826',\n", " 'CharCode': 'GBP',\n", " 'Nominal': 1,\n", " 'Name': 'Фунт стерлингов Соединенного королевства',\n", " 'Value': 85.399,\n", " 'Previous': 84.5011},\n", " 'AMD': {'ID': 'R01060',\n", " 'NumCode': '051',\n", " 'CharCode': 'AMD',\n", " 'Nominal': 100,\n", " 'Name': 'Армянских драмов',\n", " 'Value': 13.8174,\n", " 'Previous': 13.7951},\n", " 'BYN': {'ID': 'R01090B',\n", " 'NumCode': '933',\n", " 'CharCode': 'BYN',\n", " 'Nominal': 1,\n", " 'Name': 'Белорусский рубль',\n", " 'Value': 29.5946,\n", " 'Previous': 29.6037},\n", " 'BGN': {'ID': 'R01100',\n", " 'NumCode': '975',\n", " 'CharCode': 'BGN',\n", " 'Nominal': 1,\n", " 'Name': 'Болгарский лев',\n", " 'Value': 37.6417,\n", " 'Previous': 37.7591},\n", " 'BRL': {'ID': 'R01115',\n", " 'NumCode': '986',\n", " 'CharCode': 'BRL',\n", " 'Nominal': 1,\n", " 'Name': 'Бразильский реал',\n", " 'Value': 14.4352,\n", " 'Previous': 14.636},\n", " 'HUF': {'ID': 'R01135',\n", " 'NumCode': '348',\n", " 'CharCode': 'HUF',\n", " 'Nominal': 100,\n", " 'Name': 'Венгерских форинтов',\n", " 'Value': 21.9037,\n", " 'Previous': 22.0305},\n", " 'HKD': {'ID': 'R01200',\n", " 'NumCode': '344',\n", " 'CharCode': 'HKD',\n", " 'Nominal': 10,\n", " 'Name': 'Гонконгских долларов',\n", " 'Value': 85.1741,\n", " 'Previous': 85.0561},\n", " 'DKK': {'ID': 'R01215',\n", " 'NumCode': '208',\n", " 'CharCode': 'DKK',\n", " 'Nominal': 10,\n", " 'Name': 'Датских крон',\n", " 'Value': 98.5239,\n", " 'Previous': 98.8206},\n", " 'USD': {'ID': 'R01235',\n", " 'NumCode': '840',\n", " 'CharCode': 'USD',\n", " 'Nominal': 1,\n", " 'Name': 'Доллар США',\n", " 'Value': 66.1854,\n", " 'Previous': 66.0784},\n", " 'EUR': {'ID': 'R01239',\n", " 'NumCode': '978',\n", " 'CharCode': 'EUR',\n", " 'Nominal': 1,\n", " 'Name': 'Евро',\n", " 'Value': 73.6842,\n", " 'Previous': 73.7369},\n", " 'INR': {'ID': 'R01270',\n", " 'NumCode': '356',\n", " 'CharCode': 'INR',\n", " 'Nominal': 100,\n", " 'Name': 'Индийских рупий',\n", " 'Value': 90.3555,\n", " 'Previous': 89.9008},\n", " 'KZT': {'ID': 'R01335',\n", " 'NumCode': '398',\n", " 'CharCode': 'KZT',\n", " 'Nominal': 100,\n", " 'Name': 'Казахстанских тенге',\n", " 'Value': 17.3795,\n", " 'Previous': 17.3971},\n", " 'CAD': {'ID': 'R01350',\n", " 'NumCode': '124',\n", " 'CharCode': 'CAD',\n", " 'Nominal': 1,\n", " 'Name': 'Канадский доллар',\n", " 'Value': 49.381,\n", " 'Previous': 49.4747},\n", " 'KGS': {'ID': 'R01370',\n", " 'NumCode': '417',\n", " 'CharCode': 'KGS',\n", " 'Nominal': 100,\n", " 'Name': 'Киргизских сомов',\n", " 'Value': 94.7167,\n", " 'Previous': 94.5636},\n", " 'CNY': {'ID': 'R01375',\n", " 'NumCode': '156',\n", " 'CharCode': 'CNY',\n", " 'Nominal': 10,\n", " 'Name': 'Китайских юаней',\n", " 'Value': 95.3392,\n", " 'Previous': 95.3017},\n", " 'MDL': {'ID': 'R01500',\n", " 'NumCode': '498',\n", " 'CharCode': 'MDL',\n", " 'Nominal': 10,\n", " 'Name': 'Молдавских леев',\n", " 'Value': 38.0376,\n", " 'Previous': 38.0307},\n", " 'NOK': {'ID': 'R01535',\n", " 'NumCode': '578',\n", " 'CharCode': 'NOK',\n", " 'Nominal': 10,\n", " 'Name': 'Норвежских крон',\n", " 'Value': 71.3605,\n", " 'Previous': 71.3266},\n", " 'PLN': {'ID': 'R01565',\n", " 'NumCode': '985',\n", " 'CharCode': 'PLN',\n", " 'Nominal': 1,\n", " 'Name': 'Польский злотый',\n", " 'Value': 17.1518,\n", " 'Previous': 17.1976},\n", " 'RON': {'ID': 'R01585F',\n", " 'NumCode': '946',\n", " 'CharCode': 'RON',\n", " 'Nominal': 1,\n", " 'Name': 'Румынский лей',\n", " 'Value': 15.321,\n", " 'Previous': 15.3606},\n", " 'XDR': {'ID': 'R01589',\n", " 'NumCode': '960',\n", " 'CharCode': 'XDR',\n", " 'Nominal': 1,\n", " 'Name': 'СДР (специальные права заимствования)',\n", " 'Value': 91.4259,\n", " 'Previous': 91.0772},\n", " 'SGD': {'ID': 'R01625',\n", " 'NumCode': '702',\n", " 'CharCode': 'SGD',\n", " 'Nominal': 1,\n", " 'Name': 'Сингапурский доллар',\n", " 'Value': 47.7425,\n", " 'Previous': 47.6825},\n", " 'TJS': {'ID': 'R01670',\n", " 'NumCode': '972',\n", " 'CharCode': 'TJS',\n", " 'Nominal': 10,\n", " 'Name': 'Таджикских сомони',\n", " 'Value': 68.3663,\n", " 'Previous': 68.1572},\n", " 'TRY': {'ID': 'R01700J',\n", " 'NumCode': '949',\n", " 'CharCode': 'TRY',\n", " 'Nominal': 1,\n", " 'Name': 'Турецкая лира',\n", " 'Value': 10.874,\n", " 'Previous': 10.8229},\n", " 'TMT': {'ID': 'R01710A',\n", " 'NumCode': '934',\n", " 'CharCode': 'TMT',\n", " 'Nominal': 1,\n", " 'Name': 'Новый туркменский манат',\n", " 'Value': 18.9372,\n", " 'Previous': 18.9066},\n", " 'UZS': {'ID': 'R01717',\n", " 'NumCode': '860',\n", " 'CharCode': 'UZS',\n", " 'Nominal': 10000,\n", " 'Name': 'Узбекских сумов',\n", " 'Value': 69.7349,\n", " 'Previous': 69.455},\n", " 'UAH': {'ID': 'R01720',\n", " 'NumCode': '980',\n", " 'CharCode': 'UAH',\n", " 'Nominal': 10,\n", " 'Name': 'Украинских гривен',\n", " 'Value': 26.7627,\n", " 'Previous': 26.4485},\n", " 'CZK': {'ID': 'R01760',\n", " 'NumCode': '203',\n", " 'CharCode': 'CZK',\n", " 'Nominal': 10,\n", " 'Name': 'Чешских крон',\n", " 'Value': 29.0618,\n", " 'Previous': 29.2072},\n", " 'SEK': {'ID': 'R01770',\n", " 'NumCode': '752',\n", " 'CharCode': 'SEK',\n", " 'Nominal': 10,\n", " 'Name': 'Шведских крон',\n", " 'Value': 69.7834,\n", " 'Previous': 69.9524},\n", " 'CHF': {'ID': 'R01775',\n", " 'NumCode': '756',\n", " 'CharCode': 'CHF',\n", " 'Nominal': 1,\n", " 'Name': 'Швейцарский франк',\n", " 'Value': 69.2026,\n", " 'Previous': 69.2355},\n", " 'ZAR': {'ID': 'R01810',\n", " 'NumCode': '710',\n", " 'CharCode': 'ZAR',\n", " 'Nominal': 10,\n", " 'Name': 'Южноафриканских рэндов',\n", " 'Value': 43.149,\n", " 'Previous': 43.0041},\n", " 'KRW': {'ID': 'R01815',\n", " 'NumCode': '410',\n", " 'CharCode': 'KRW',\n", " 'Nominal': 1000,\n", " 'Name': 'Вон Республики Корея',\n", " 'Value': 55.9575,\n", " 'Previous': 55.7642},\n", " 'JPY': {'ID': 'R01820',\n", " 'NumCode': '392',\n", " 'CharCode': 'JPY',\n", " 'Nominal': 100,\n", " 'Name': 'Японских иен',\n", " 'Value': 61.7027,\n", " 'Previous': 61.5112}}" ] }, "execution_count": 64, "metadata": {}, "output_type": "execute_result" } ], "source": [ "r.exchange_rates()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Документация необходима почти всем методам" ] }, { "cell_type": "code", "execution_count": 65, "metadata": {}, "outputs": [], "source": [ "?r.exchange_rates" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Система повышения сотрудников" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Упражнение\n", "Создайте класс Employee. При инициализации указываются имя сотрудника (name) и трудовой стаж в пройденных аккредитациях (seniority). Напишите метод init, в котором задаются соответствующие переменные - self.name и self.seniority." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Упражнение\n", "Заведите переменную self.grade при инициализации класса со значением 0. Добавьте метод grade_up, который увеличивает это значение на 1. На всякий случай - этот метод может ничего не возвращать, только изменять переменную." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Наследование" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Разработчикам финансового департамента помимо курса надо работать с кодами валют. Как сохранить сохранить разработку класса Rate у нас, а полезные функции передать финансистам?" ] }, { "cell_type": "code", "execution_count": 66, "metadata": {}, "outputs": [], "source": [ "class CurrencyCodes(Rate):\n", " def __init__(self):\n", " super().__init__(format_='full')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Теперь классу CurrencyCodes доступны все методы класса Rate. Можем продолжать разработку в нужном направлении." ] }, { "cell_type": "code", "execution_count": 67, "metadata": {}, "outputs": [], "source": [ "cc = CurrencyCodes()" ] }, { "cell_type": "code", "execution_count": 68, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "{'ID': 'R01235',\n", " 'NumCode': '840',\n", " 'CharCode': 'USD',\n", " 'Nominal': 1,\n", " 'Name': 'Доллар США',\n", " 'Value': 66.1854,\n", " 'Previous': 66.0784}" ] }, "execution_count": 68, "metadata": {}, "output_type": "execute_result" } ], "source": [ "CurrencyCodes().usd()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Допишем в класс что-нибудь свое новенькое" ] }, { "cell_type": "code", "execution_count": 69, "metadata": {}, "outputs": [], "source": [ "class CurrencyCodes(Rate):\n", " def __init__(self):\n", " super().__init__(format_='full')\n", " \n", " def currency_id(self, currency):\n", " \"\"\"Получение идентификатора валюты\"\"\"\n", " return self.make_format(currency)['ID']" ] }, { "cell_type": "code", "execution_count": 70, "metadata": {}, "outputs": [], "source": [ "currency = CurrencyCodes()" ] }, { "cell_type": "code", "execution_count": 71, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "'R01235'" ] }, "execution_count": 71, "metadata": {}, "output_type": "execute_result" } ], "source": [ "currency.currency_id('USD')" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Система повышения сотрудников\n", "Пригодится для домашнего задания" ] }, { "cell_type": "code", "execution_count": 72, "metadata": {}, "outputs": [], "source": [ "class Employee:\n", " def __init__(self, name, seniority):\n", " self.name = name\n", " self.seniority = seniority\n", " \n", " self.grade = 1\n", " \n", " def grade_up(self):\n", " \"\"\"Повышает уровень сотрудника\"\"\"\n", " self.grade += 1\n", " \n", " def publish_grade(self):\n", " \"\"\"Публикация результатов аккредитации сотрудников\"\"\"\n", " print(self.name, self.grade)\n", " \n", " def check_if_it_is_time_for_upgrade(self):\n", " pass" ] }, { "cell_type": "code", "execution_count": 73, "metadata": {}, "outputs": [], "source": [ "class Developer(Employee):\n", " def __init__(self, name, seniority):\n", " super().__init__(name, seniority)\n", " \n", " def check_if_it_is_time_for_upgrade(self):\n", " # для каждой аккредитации увеличиваем счетчик на 1\n", " # пока считаем, что все разработчики проходят аккредитацию\n", " self.seniority += 1\n", " \n", " # условие повышения сотрудника из презентации\n", " if self.seniority % 5 == 0:\n", " self.grade_up()\n", " \n", " # публикация результатов\n", " return self.publish_grade()" ] }, { "cell_type": "code", "execution_count": 74, "metadata": {}, "outputs": [], "source": [ "# проверяем как работает система повышения сотрудников на примере отдела разработки\n", "\n", "# разработчик Александр только что пришел в компанию\n", "alex = Developer('Александр', 0)" ] }, { "cell_type": "code", "execution_count": 75, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Александр 1\n", "Александр 1\n", "Александр 1\n", "Александр 1\n", "Александр 2\n", "Александр 2\n", "Александр 2\n", "Александр 2\n", "Александр 2\n", "Александр 3\n", "Александр 3\n", "Александр 3\n", "Александр 3\n", "Александр 3\n", "Александр 4\n", "Александр 4\n", "Александр 4\n", "Александр 4\n", "Александр 4\n", "Александр 5\n" ] } ], "source": [ "for i in range(20):\n", " alex.check_if_it_is_time_for_upgrade()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Домашнее задание задача 3\n", "\n", "Напишите класс Designer, который учитывает количество международных премий для дизайнеров (из презентации: \"Повышение на 1 грейд за каждые 7 баллов. Получение международной премии – это +2 балла\"). Считайте, что при выходе на работу сотрудник уже имеет две премии и их количество не меняется со стажем (конечно если хотите это можно вручную менять). Выполните проверку для 20 аккредитаций дизайнера Елены.\n", "\n", "Для проверки используйте код:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "elena = Designer('Елена', seniority=0, awards=2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for i in range(20):\n", " elena.check_if_it_is_time_for_upgrade()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Импорт классов и функций" ] }, { "cell_type": "code", "execution_count": 76, "metadata": {}, "outputs": [], "source": [ "from libs.exchange import my_sum" ] }, { "cell_type": "code", "execution_count": 77, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "3" ] }, "execution_count": 77, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_sum(1, 2)" ] }, { "cell_type": "code", "execution_count": 78, "metadata": {}, "outputs": [], "source": [ "from libs.exchange import Rate" ] }, { "cell_type": "code", "execution_count": 79, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "39.0129" ] }, "execution_count": 79, "metadata": {}, "output_type": "execute_result" } ], "source": [ "Rate().AZN()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# такой способ импорта крайне не рекомендуется\n", "from libs.exchange import *" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Если библиотека лежит в произвольной папке" ] }, { "cell_type": "code", "execution_count": 80, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['/Users/kbashevoy/Desktop/Нетология/Занятия/Занятие 8',\n", " '/Users/kbashevoy/anaconda3/lib/python37.zip',\n", " '/Users/kbashevoy/anaconda3/lib/python3.7',\n", " '/Users/kbashevoy/anaconda3/lib/python3.7/lib-dynload',\n", " '',\n", " '/Users/kbashevoy/.local/lib/python3.7/site-packages',\n", " '/Users/kbashevoy/anaconda3/lib/python3.7/site-packages',\n", " '/Users/kbashevoy/anaconda3/lib/python3.7/site-packages/aeosa',\n", " '/Users/kbashevoy/anaconda3/lib/python3.7/site-packages/IPython/extensions',\n", " '/Users/kbashevoy/.ipython']" ] }, "execution_count": 80, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import sys\n", "sys.path" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import sys\n", "sys.path.append('адрес_папки_с_файлами')" ] }, { "cell_type": "code", "execution_count": 81, "metadata": {}, "outputs": [], "source": [ "# пример\n", "\n", "import sys\n", "sys.path.append('/Users/kbashevoy/Desktop/Нетология/Занятия/Занятие 8/libs')" ] }, { "cell_type": "code", "execution_count": 82, "metadata": {}, "outputs": [], "source": [ "from exchange import my_sum" ] }, { "cell_type": "code", "execution_count": 83, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6" ] }, "execution_count": 83, "metadata": {}, "output_type": "execute_result" } ], "source": [ "my_sum(3, 3)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.0" } }, "nbformat": 4, "nbformat_minor": 2 }