> For the complete documentation index, see [llms.txt](https://interlink.gitbook.io/process/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://interlink.gitbook.io/process/dev/development/technologies/programming-languages/python.md).

# Python

**Темы для изучения**

* Pip
* Conda/Virtualenv
* Djabgo
* Django Admin
* Django REST Framework
* manage.py - shell, runserver, makemigrations, migrate, dbshell, createsuperuser
* Debugging
* Logging
* Login & registration, JWT
* Form/ModelForm
* Production
* Декомпозиция моделей, views
* Metaprogramming. Динамическое создание классов DynamicClass = type('DynamicClass', (), {'spam': 'eggs'})
* RTTI получаем информацию к внутренней структуре класса
* Generators
* Functions: callable, len, str, repr
* Properties: \_\_getitem\_\_,  \_\_setitem\_\_, \_\_call\_\_, \_\_init\_\_, \_\_get\_\_, \_\_set\_\_, \_\_dict\_\_,&#x20;  &#x20;\_\_str\_\_ , \_\_len\_\_, \_\_iter\_\_
* Декораторы (обертки)  &#x20;@decorate
* Partial objects
* Descriptors
* Exceptions
* None
* Wsgi
* Flask/Flask-AppBuilder
* PEP8
* [Celery](http://www.celeryproject.org/), a distributed task queue
* Twisted - an event-driven networking engine written in Python and licensed under the open source
* Percona Server for MySQL is a free, fully compatible, enhanced, and open source drop-in replacement for any MySQL database. It provides superior performance, scalability, and instrumentation.

//декларации внутри класса выполняются немедленно&#x20;

`class NormalClass:` \
`... print('Loading NormalClass')` \
`... spam = 'eggs'` \
`... print('Done loading')`

//динамическое создание класса&#x20;

`DynamicClass = type('DynamicClass', (), {'spam': 'eggs'})`

//metaclass - класс который создает другие классы (metaprogramming динамич создание классов во время выполнения) \
//получаем информацию к внутренней структуре класса&#x20;

`class MetaClass(type):` \
`... def __init__(cls, name, bases, attrs):` \
`... print('Defining %s' % cls)` \
`... print('Name: %s' % name)` \
`... print('Bases: %s' % (bases,))` \
`... print('Attributes:')` \
`... for (name, value) in attrs.items():` \
`... print(' %s: %r' % (name, value))`

// empty class body&#x20;

`class SubClass(RealClass): # Notice there's no metaclass here.` \
`... pass`

// declarative syntax&#x20;

`class Contact(models.Model):` \
&#x20;   `"""` \
&#x20;   `Contact information provided when sending messages to the owner of the site.` \
&#x20;   `"""` \
&#x20;   `name = models.CharField(max_length=255)` \
&#x20;   `email = models.EmailField()`

`from django.db import models`\
`class Contact(models.Model):` \
&#x20;   `name = models.CharField(max_length=255)` \
&#x20;   `email = models.EmailField()`

//в декларативном синтаксисе питон не гаранирует порядок выполнения, поэтому можно сделать свой класс аттрубута который бы отслеживал последовательность создания&#x20;

`class BaseAttribute(object):` \
&#x20;   `creation_counter = 1` \
&#x20;   `def __init__(self):` \
&#x20;       `self.creation_counter = BaseAttribute.creation_counter` \
&#x20;       `BaseAttribute.creation_counter += 1`

//\_\_call\_\_ когда объект используется как функция, например times = Multiplier(2) и затем times(5)&#x20;

`class Multiplier(object):` \
`... def __init__(self, factor):` \
`... self.factor = factor` \
`... def __call__(self, value):` \
`... return value * self.factor`

// проверка может ли объект использовать как функция&#x20;

`b = Basic()` \
`callable(b)`

// словари dictionaries&#x20;

`class CaseInsensitiveDict(dict):` \
`... def __init__(self, **kwargs):` \
`...     for key, value in kwargs.items():` \
`...         self[key.lower()] = value` \
`... def __contains__(self, key):` \
`...     return super(CaseInsensitiveDict, self).__contains__(key.lower())` \
`... def __getitem__(self, key):` \
`...     return super(CaseInsensitiveDict, self).__getitem__(key.lower())` \
`... def __setitem__(self, key, value):` \
`...     super(CaseInsensitiveDict, self).__setitem__(key.lower(), value)`

`... d = CaseInsensitiveDict(SpAm='eggs') print('spam' in d) d['sPaM'] = 'burger'`

//итераторы&#x20;

`class Fibonacci(object):` \
`... def __init__(self, count):` \
`...     self.count = count` \
`... def __iter__(self):` \
`...     a, b = 0, 1` \
`...     for x in range(self.count):` \
`...         if x < 2:` \
`...             yield x` \
`...         else:` \
`...             c = a + b` \
`...             yield c` \
`...             a, b = b, c` \
`...` \
`for x in Fibonacci(5):` \
`print(x)`

//stop iteration&#x20;

`raise StopIteration`

//new name for *next*&#x20;

`class FibonacciIterator(object):` \
`def __next__(self):` \
`...` \
`next = __next__ #python3 name is next() by default`

//generators - похожи на итераторы\
//sequence - набор объектов

`//встроенная функция len() и ее реализация __len__(self)` \
`//проперти __getitem__(self) and __setitem__(self, value)`

//переменное кол-во аргументов функции&#x20;

`def multiply(*args):` \
`... total = 1` \
`... for arg in args:` \
`... total *= arg` \
`... return total` \
`... multiply(2, 3) multiply(2, 3, 4, 5, 6)`

//пара ключ значение в аргументах&#x20;

`def accept(**kwargs):` \
`... for keyword, value in kwargs.items():` \
`... print("%s -> %r" % (keyword, value))` \
`...` \
`accept(foo='bar', spam='eggs')`

//аргументы \
• Required arguments \
• Optional arguments \
• Excess positional arguments \
• Excess keyword arguments kwargs = {'b': 8, 'c': 9}&#x20;

def complex\_function(a, b=None, \*c, \*\*d):

//декораторы (обертки)&#x20;

`def decorate(func):` \
`... print('Decorating %s...' % func.__name__)` \
`... def wrapped(*args, **kwargs):` \
`...     print("Called wrapped function with args:", args)` \
`...     return func(*args, **kwargs)` \
`... print('done!')` \
`... return wrapped` \
\
`... @decorate` \
`... def test(a, b):` \
`...     return a + b`

//partial object\
//descriptors&#x20;

`import datetime` \
`class CurrentDate(object):` \
&#x20;    `def __get__(self, instance, owner):` \
&#x20;         `return datetime.date.today()` \
&#x20;    `def __set__(self, instance, value):` \
&#x20;         `raise NotImplementedError("Can't change the current date.")`

`class Example(object):` \
`date = CurrentDate()`

`e = Example()` \
`e.date` \
`datetime.date(2008, 11, 24)` \
`e.date = datetime.date.today() # доступ к полю класса`

//константа None

//&#x20;

`class Descriptor(object):` \
`... def __init__(self, name):` \
`...     self.name = name` \
`... def __get__(self, instance, owner):` \
`...     return instance.__dict__[self.name]` \
`... def __set__(self, instance, value):` \
`...     instance.__dict__[self.name] = value` \
`...` \
`class TestObject(object):` \
&#x20;   `attr = Descriptor('attr')` \
`...`\
`>>>test = TestObject()` \
`>>>test.attr = 6` \
`>>>test.attr` \
`6`

//переопределение toString()&#x20;

`def __str__(self): return '{} ({})'.format(self.title, self.year)`

\ - перенос строки

//multiline comment&#x20;

""" mmm """

//создать переменную класса&#x20;

self.bucketlist\_name = "Write world class code"

`str(o) // вызов __str__(self)` \
`repr(o) //внутренее представление объекта (RTTI)`

//выключить проверку для view&#x20;

@csrf\_exempt \
def snippet\_list(request): \
&#x20;   pass

try: \
&#x20;   snippet = Snippet.objects.get(pk=pk) \
except Snippet.DoesNotExist: \
&#x20;   return HttpResponse(status=404)

**Дополнительные источники**

* Книга по Python. Pro Python 3: Features and Tools for Professional Development
* Асинхронное программирование <https://habr.com/ru/company/ruvds/blog/475246/>
* 26 полезных приёмов и хитростей Python <https://tproger.ru/translations/an-a-z-of-python-tricks/>
* <http://www.youtube.com/watch?v=xKtv8\\_9HJNA\\&list=SP26BA8B9FC33789FF>
* ORM - sqlAlchemy <http://www.sqlalchemy.org/>
* JSON message pack <http://msgpack.org/>
* tornado/other lightweight frameworks <http://www.tornadoweb.org/> WebServer
* <http://www.simeonfranklin.com/python-fundamentals/&#x20>;
* <http://www.simeonfranklin.com/python-fundamentals.pdf>
* <http://docs.python.org/3/&#x20>;
* <http://docs.python.org/3/library/index.html>
* <http://www.simeonfranklin.com/pro-django-class/>
* Flask + Jinja frameworks <http://flask.pocoo.org/>
* Scrapy frame work - scraping using python
* pep8 <http://www.python.org/dev/peps/pep-0008/>
* обзор web фреймворков <http://www.infoworld.com/d/application-development/pillars-python-six-python-web-frameworks-compared-169442?page=0,0>
* <http://wiki.python.org/moin/WebFrameworks&#x20>;
* <http://www.pythondiary.com/blog/Feb.14,2012/too-many-micro-webframeworks.html>
* <http://blog.fruiapps.com/2012/05/Choose-your-Python-Web-Framework-the-Hard-Way>
* blogs <http://www.pythondiary.com/blog/>
* success stories <http://www.revolunet.com/static/django-success-stories/#1>
