Лекция 4
  Python
Особенности
❖ Интерпретируемый
❖ Высокоуровневый
❖ Объектно-ориентированный
❖ Пакеты  на все случаи жизни
❖ Код легко читается
❖ Кроссплатформенный
>>> import this                     Дзэн Питона
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Реализации
❖ Jython
❖ PyPy
❖ IronPython
❖ Cython
❖ CPython
  ❖ 2.5,   2.6 и 2.7
  ❖ 3.x
Hello World!
# coding: utf-8

persons = (u'Петя', u'Вася', u'Коля', u'Саша', )

# итерируем по списку
for person in persons:
   print u'Привет', person
print u'done...'


$ python hello_world.py
Привет Петя
Привет Вася
Привет Коля
Привет Саша
done...
Hello World! v2
# coding: utf-8

"""Print greetings for the persons.
This is multiline comment."""

def greeting(person, index = None):
  if index is None:
      return u'Привет %s!' % person
  else:
      return u'%s. Привет %s!' % (index, person)
  return

persons = (u'Петя', u'Вася', )
for i, person in enumerate(persons):
   print greeting(person, i)


$ python hello_world2.py
0. Привет Петя!
1. Привет Вася!
# coding: utf-8
                    Hello World! v2
u"""Print greetings for the persons.
This is multiline comment."""

def greeting(person, index = None):
  return u'%s. Привет %s!' % (index, person)

persons = (u'Петя', u'Вася', )
for i, person in enumerate(persons):
   print greeting(person, I)

$ python
>>> import hello_world2
0. Привет Петя!
1. Привет Вася!
>>> hello_world2.greeting('Noname')
u'None. Привет Noname!'
>>> hello_world2.persons
(u'Петя', u'Вася')
>>> hello_world2.__doc__
'Print greetings for the persons.This is multiline comment.'
Словари
>>> # работа со структурами данных
...
>>> dict()
{}
>>> d = {'server': 'localhost', 'port': 22}
>>> pass
>>> d['server'] = '127.0.0.1'
>>> d[42] = ('Life', 'Question')
>>> d
{42: ('Life', 'Question'), 'port': 22, 'server': '127.0.0.1'}
>>> list()                                  Списки
[]
>>> l = [42, dict(), [0, 1, 2]]
>>> l[0]
42
>>> l[1]['message'] = 'empty'
>>> pass
>>> l[2].append(3)
>>> l[-1].extend(['four', 'five'])
>>> pass
>>> l.insert(0, 'new')
>>> l[1:]
[42, {'message': 'empty'}, [0, 1, 2, 3, 'four', 'five']]
>>> del l[0]
>>> l.index(42)
0
>>> l.remove(42)
>>> l.pop() + ['six']
[0, 1, 2, 3, 'four', 'five', 'six']
>>> l
[{'message': 'empty'}]
Строки
>>> l = ('Hello', 'beatiful', 'world')
>>> s = u' '.join(l)
>>> s
u'Hello beatiful world'
>>> s.split()
[u'Hello', u'beatiful', u'world']
>>> pass
>>> s.upper()
u'HELLO BEATIFUL WORLD'
>>> s.lower()
u'hello beatiful world'
>>> str(1)
'1'
>>> pass
>>> str(l)
"('Hello', 'beatiful', 'world')"
>>> unicode(None)
u'None'
Переменные
>>> v = ('a','b','e')
>>> (x, y, z) = v
>>> if True:
. . . k, l = 10, 20
...
>>> k, l
(10, 20)
Builtins
>>> l = list()
>>> dir(l)
['__add__', ... , 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove',
'reverse', 'sort']
>>> import math
>>> dir(math)
['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan',
'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs',
'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log',
'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh',
'trunc']
>>> getattr(l, 'append')
<built-in method append of list object at 0xb74598ac>
>>> getattr(l, 'append')('1')
>>> type(l)
<type 'list'>
>>> help(dir)
справка ...
>>> file('/etc/hosts', 'r')
<open file '/etc/hosts', mode 'r' at 0xb7794128>
Логические операции
>>> 'a' or 'b'
'a'
>>> '' or 'b'
'b'
>>> '' or [] or {}
{}
>>> True or print('Hello')
>>> True or int(noname)
>>> x = 'A' if 5 in range(10) else 'B'
>>> x
'A'
Средства разработки
❖ python
  ❖    print
❖ ipython/bpython
  ❖   справка
  ❖   автодополнение
  ❖   история команд и результатов

❖ pdb
❖ PyPi
  ❖ easy_install
  ❖ pip     + vitrtualenv
ООП
# coding: utf-8

class FileInfo(object):
   u"хранит метаинформацию о файле"
   def __init__(self, filename=None):
     self.filename = filename
     self.name = filename or 'unknown'
     self.ext = None

  def __unicode__(self):
    return self.ext + u' - ' + self.filename

class MP3FileInfo(FileInfo):

  def __init__(self, *args, **kwargs):
    super(MP3FileInfo, self).__init__(*args, **kwargs)
    self.ext = 'mp3'

f = MP3FileInfo('example')
print unicode(f)
Обработка исключений
try:
   # Здесь код, который может вызвать исключение
   raise Exception("message")
except (Тип исключения1, Тип исключения2, …), Переменная:
   # Обработка исключения
   raise
except (Тип исключения3, Тип исключения4, …), Переменная:
   # Обработка исключения
   pass
except:
   # Обработка любого другого исключения
   pass
else:
   # Если исключения не было
   pass
finally:
   # Код, исполняемый в любом случае
   pass

Python

  • 1.
  • 2.
    Особенности ❖ Интерпретируемый ❖ Высокоуровневый ❖Объектно-ориентированный ❖ Пакеты на все случаи жизни ❖ Код легко читается ❖ Кроссплатформенный
  • 3.
    >>> import this Дзэн Питона The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!
  • 4.
    Реализации ❖ Jython ❖ PyPy ❖IronPython ❖ Cython ❖ CPython ❖ 2.5, 2.6 и 2.7 ❖ 3.x
  • 5.
    Hello World! # coding:utf-8 persons = (u'Петя', u'Вася', u'Коля', u'Саша', ) # итерируем по списку for person in persons: print u'Привет', person print u'done...' $ python hello_world.py Привет Петя Привет Вася Привет Коля Привет Саша done...
  • 6.
    Hello World! v2 #coding: utf-8 """Print greetings for the persons. This is multiline comment.""" def greeting(person, index = None): if index is None: return u'Привет %s!' % person else: return u'%s. Привет %s!' % (index, person) return persons = (u'Петя', u'Вася', ) for i, person in enumerate(persons): print greeting(person, i) $ python hello_world2.py 0. Привет Петя! 1. Привет Вася!
  • 7.
    # coding: utf-8 Hello World! v2 u"""Print greetings for the persons. This is multiline comment.""" def greeting(person, index = None): return u'%s. Привет %s!' % (index, person) persons = (u'Петя', u'Вася', ) for i, person in enumerate(persons): print greeting(person, I) $ python >>> import hello_world2 0. Привет Петя! 1. Привет Вася! >>> hello_world2.greeting('Noname') u'None. Привет Noname!' >>> hello_world2.persons (u'Петя', u'Вася') >>> hello_world2.__doc__ 'Print greetings for the persons.This is multiline comment.'
  • 8.
    Словари >>> # работасо структурами данных ... >>> dict() {} >>> d = {'server': 'localhost', 'port': 22} >>> pass >>> d['server'] = '127.0.0.1' >>> d[42] = ('Life', 'Question') >>> d {42: ('Life', 'Question'), 'port': 22, 'server': '127.0.0.1'}
  • 9.
    >>> list() Списки [] >>> l = [42, dict(), [0, 1, 2]] >>> l[0] 42 >>> l[1]['message'] = 'empty' >>> pass >>> l[2].append(3) >>> l[-1].extend(['four', 'five']) >>> pass >>> l.insert(0, 'new') >>> l[1:] [42, {'message': 'empty'}, [0, 1, 2, 3, 'four', 'five']] >>> del l[0] >>> l.index(42) 0 >>> l.remove(42) >>> l.pop() + ['six'] [0, 1, 2, 3, 'four', 'five', 'six'] >>> l [{'message': 'empty'}]
  • 10.
    Строки >>> l =('Hello', 'beatiful', 'world') >>> s = u' '.join(l) >>> s u'Hello beatiful world' >>> s.split() [u'Hello', u'beatiful', u'world'] >>> pass >>> s.upper() u'HELLO BEATIFUL WORLD' >>> s.lower() u'hello beatiful world' >>> str(1) '1' >>> pass >>> str(l) "('Hello', 'beatiful', 'world')" >>> unicode(None) u'None'
  • 11.
    Переменные >>> v =('a','b','e') >>> (x, y, z) = v >>> if True: . . . k, l = 10, 20 ... >>> k, l (10, 20)
  • 12.
    Builtins >>> l =list() >>> dir(l) ['__add__', ... , 'append', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] >>> import math >>> dir(math) ['__doc__', '__name__', '__package__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'trunc'] >>> getattr(l, 'append') <built-in method append of list object at 0xb74598ac> >>> getattr(l, 'append')('1') >>> type(l) <type 'list'> >>> help(dir) справка ... >>> file('/etc/hosts', 'r') <open file '/etc/hosts', mode 'r' at 0xb7794128>
  • 13.
    Логические операции >>> 'a'or 'b' 'a' >>> '' or 'b' 'b' >>> '' or [] or {} {} >>> True or print('Hello') >>> True or int(noname) >>> x = 'A' if 5 in range(10) else 'B' >>> x 'A'
  • 14.
    Средства разработки ❖ python ❖ print ❖ ipython/bpython ❖ справка ❖ автодополнение ❖ история команд и результатов ❖ pdb ❖ PyPi ❖ easy_install ❖ pip + vitrtualenv
  • 15.
    ООП # coding: utf-8 classFileInfo(object): u"хранит метаинформацию о файле" def __init__(self, filename=None): self.filename = filename self.name = filename or 'unknown' self.ext = None def __unicode__(self): return self.ext + u' - ' + self.filename class MP3FileInfo(FileInfo): def __init__(self, *args, **kwargs): super(MP3FileInfo, self).__init__(*args, **kwargs) self.ext = 'mp3' f = MP3FileInfo('example') print unicode(f)
  • 16.
    Обработка исключений try: # Здесь код, который может вызвать исключение raise Exception("message") except (Тип исключения1, Тип исключения2, …), Переменная: # Обработка исключения raise except (Тип исключения3, Тип исключения4, …), Переменная: # Обработка исключения pass except: # Обработка любого другого исключения pass else: # Если исключения не было pass finally: # Код, исполняемый в любом случае pass