|
|
|
|
Язык Python
Предисловие
1. Знакомство с языком Python
- 1.1. В глубь
- 1.2. Объявление функций
- 1.3. Документирование функций
- 1.4. Все является объектами
- 1.5. Отступы
- 1.6. Тестирование модулей
- 1.7. Словари
- 1.8. Списки
- 1.9. Кортежи
- 1.10. Определение переменных
- 1.11. Присваивание сразу нескольких значений
- 1.12. Форматированное представление
- 1.13. Обработка списков
- 1.14. Объединение и разбиение строк
- 1.15. Заключение
|
|
Подробнее...
|
|
Эта книга не предназначена для новичков. Подразумевается, что:
- Вы уже знакомы хотябы с одним объектно-ориентированным языком, таким как Java, C++, или Delphi.
- Вы знаете хотябы один скриптовой язык, например, Perl, Visual Basic, или JavaScript.
- Вы уже установили Python версии 2.0 или выше (рекомендуется Python 2.2) для Windows, UNIX, Mac OS X, Mac OS или любой другой поддерживаемой платформы. Случаи, кода разница между версиями 2.0 и 2.2 существенна, будут отдельно оговорены в тексте.
- Вы загрузили примеры программ, используемых в этой книге.
|
|
Подробнее...
|
Здесь представлена полноценная программа на языке Python.
Возможно эта программа не представляет для вас никакого смысла. Не беспокойтесь, мы проанализируем каждую строку. Но сначала прочитайте ее и посмотрите, в чем вы смогли разобраться самостоятельно. |
|
Подробнее...
|
|
В языке Python, как и в большинстве других языков программирования, есть функции, но в нем нет отдельных заголовочных файлов, как в C++, или разделов интерфейс/реализация, как в языке Pascal. Если вам нужна функция — просто определите ее. |
|
Подробнее...
|
|
В языке Python вы можете документировать функции, снабжая их строками документации. |
|
Подробнее...
|
|
Если вы не обратили внимание, я только что заметил, что функции в языке Python имеют атрибуты, и эти атрибуты доступны во время выполнения программы.
Функция, как и все остальное в языке Python, является объектом.
|
|
Подробнее...
|
В определении функций нет явных begin и end, нет фигурных скобок, обозначающих начало и конец тела функции. Единственным разделителем является двоеточие (“:”) плюс отсуп кода в теле функции.
|
|
Подробнее...
|
|
Модули в языке Python также являются объектами и имеют несколько полезных атрибутов. Вы можете использовать их, например, для тестирования. |
|
Подробнее...
|
|
Сделаем небольшое отступление, так как вам необходимо познакомиться со словарями, кортежами и списками. Если вы знаток Perl, то уже имеете некоторое представление о словарях и списках, но вам, тем не менее, необходимо обратить внимание на кортежи. |
|
Подробнее...
|
|
Список являются одним из самых используемых типов данных в языке Python. Если все ваше знакомство со списками ограничивается массивами в Visual Basic или (не дай бог) datastore в Powerbuilder, возмите себя в руки для знакомства со списками в языке Python. |
|
Подробнее...
|
|
Кортеж — это неизменяемый список. С момента создания кортеж не может быть изменен никакими способами. |
|
Подробнее...
|
|
После того, как вы познакомились со словарями, кортежами и списками, давайте вернемся к нашему примеру программы — odbchelper.py. |
|
Подробнее...
|
|
Одна из приятных возможностей языка Python — использование последовательностей для односременного присваивания нескольких значений. |
|
Подробнее...
|
|
Python позволяет получить форматированное представление значений в виде строки. Хотя строка формата может содержать довольно сложные выражения, чаще всего используется вставка значений в строку с помощью шаблона %s. |
|
Подробнее...
|
|
Одна из самых мощных особенностей языка Python — расширенная запись списков, которая позволяет легко преобразовать один список в другой, применяя к каждому элементу функцию. |
|
Подробнее...
|
|
Вы имеете список строк с парами ключ-значение вида key=value и хотите объединить их в одну строку. Для этих целей можно воспользоваться методом join строковых объектов. |
|
Подробнее...
|
|
Теперь программа odbchelper.py и ее вывод приобретают смысл. |
|
Подробнее...
|
|
Эта глава описывает одну из самых сильных возможностей языка Python — самоанализ. Ка вы уже знаете, все в языке Python является объектами. Самоанализ — использование специального кода для просмотра в памяти модулей и функций как объектов, извлекая информацию о них и о том, как их использовать. По ходу мы будем определять функции без имени, передавать аргументы в неправильном порядке и использовать функции, имена которых до этого даже не знали. |
|
Подробнее...
|
|
В языке Python аргументы функции могут иметь значения по умолчанию, оно будет использовано, если при вызове функции значение этого аргумента не указано. Более того, аргументы имеющие значение по умолчанию при вызове могут быть указаны в произвольном порядке, если указано имя аргумента. В хранимых процедурах для SQL сервера Transact/SQL также могут быть использованы именованные аргументы; если вы пишите сценарии для SQL сервера, можете лишь бегло ознакомиться с этим разделом. |
|
Подробнее...
|
|
В языке Python есть небольшой набор очень полезных встроенных функций. Все остальные функции распределены по модулям. В самом деле, это удачное проектное решение позволяет предотвратить разбухание ядра языка, как это произошло с некоторыми другими скриптовыми языками (например, Visual Basic). |
|
Подробнее...
|
|
Вы уже знаете, что функции в языке Python являются объектами. Но вы пока не знаете, что если имя функции становится известно только во время выполнения программы, то ее можно получить с помощью функции getattr. |
|
Подробнее...
|
|
Как вы уже знаете, Python позволяет преобразовывать списки с помощью расширенной записи. Такой подход можно комбинировать с фильтрованием, когда некоторые элементы отображаются, в то время как другие пропускаются. |
|
Подробнее...
|
|
В языке Python операторы and и or, как вы и ожидали, выполняют булевы операции, но они не возвращают булевы значения: результатом всегда является значение одного из операндов. |
|
Подробнее...
|
|
Python поддерживает интересный синтаксис, позволяющий определять небольшие однострочные функции на лету. Позаимствованные из Lisp, так назыаемые lambda-функции могут быть использованы везде, где требуется функция. |
|
Подробнее...
|
|
Последняя строка кода и единственная еще не разобранная — делает всю работу. Но теперь задача совсем проста, так как все, что нам необходимо, уже готово. Все костяшки домино на месте, осталось только толкнуть их. |
|
Подробнее...
|
|
Начиная с этой главы мы будем иметь дело с объектно ориентированным программированием на языке Python. Помните, я говорил, что вам необходимо знать объектно-ориентированный язык для чтения этой книги? Так я не шутил. |
|
Подробнее...
|
|
В языке Python есть два способа импортировать модули. Оба из них полезны, и вы должны знать, когда каждый из них лучше использовать. С одним способом, import module, вы уже ознакомились в главе 1. Второй способ делает примерно то же самое, но в его работе есть несколько важных отличий. |
|
Подробнее...
|
|
Python имеет полноценную поддержку объектно-ориентированного программирования: вы божете определять собственные классы, наследоваться от встроенных и собственных классов, создавать экземпляры определенных вами классов. |
|
Подробнее...
|
|
Создать экземпляр класса очень просто: достаточно вызвать класс, как если бы он был функцией, передав аргменты, определенные в методе __init__. Возвращаемое значение и есть созданный объект. |
|
Подробнее...
|
|
As you've seen, FileInfo is a class that acts like a dictionary. To explore this further, let's look at the UserDict class in the UserDict module, which is the ancestor of our FileInfo class. This is nothing special; the class is written in Python and stored in a .py file, just like our code. In particular, it's stored in the lib directory in your Python installation. |
|
Подробнее...
|
|
In addition to normal class methods, there are a number of special methods which Python classes can define. Instead of being called directly by your code (like normal methods), special methods are |
|
Подробнее...
|
|
There are more special methods than just __getitem__ and __setitem__. Some of them let you emulate functionality that you may not even know about. |
|
Подробнее...
|
|
You already know about data attributes, which are variables owned by a specific instance of a class. Python also supports class attributes, which are variables owned by the class itself. |
|
Подробнее...
|
|
Like most languages, Python has the concept of private functions, which can not be called from outside their module; private class methods, which can not be called from outside their class; and private attributes, which can not be accessed from outside their class. Unlike most languages, whether a Python function, method, or attribute is private or public is determined entirely by its name. |
|
Подробнее...
|
|
Like many object-oriented languages, Python has exception handling via try...except blocks. |
|
Подробнее...
|
|
Python has a built-in function, open, for opening a file on disk. open returns a file object, which has methods and attributes for getting information about and manipulating the opened file. |
|
Подробнее...
|
|
Most other languages don't have a powerful list datatype like Python, so you end up doing a lot of manual work, specifying a start, end, and step to define a range of integers or characters or other iteratable entities. But in Python, a for loop simply iterates over a list, the same way list comprehensions work. |
|
Подробнее...
|
|
Modules, like everything else in Python, are objects. Once imported, you can always get a reference to a module through the global dictionary sys.modules. |
|
Подробнее...
|
|
The os module has lots of useful functions for manipulating files and processes, and os.path has functions for manipulating file and directory paths. |
|
Подробнее...
|
|
Once again, all the dominoes are in place. We've seen how each line of code works. Now let's step back and see how it all fits together. |
|
Подробнее...
|
|
The fileinfo.py program should now make perfect sense. |
|
Подробнее...
|
|
Version 1.1, March 2000
Copyright (C) 2000 Free Software Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
|
|
Подробнее...
|
|
This License applies to any manual or other work that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. The "Document", below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as "you". |
|
Подробнее...
|
|
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. |
|
Подробнее...
|
|
If you publish printed copies of the Document numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. |
|
Подробнее...
|
|
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: |
|
Подробнее...
|
|
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice. |
|
Подробнее...
|
|
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. |
|
Подробнее...
|
|
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, does not as a whole count as a Modified Version of the Document, provided no compilation copyright is claimed for the compilation. Such a compilation is called an "aggregate", and this License does not apply to the other self-contained works thus compiled with the Document, on account of their being thus compiled, if they are not themselves derivative works of the Document. |
|
Подробнее...
|
|
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. |
|
Подробнее...
|
|
You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. |
|
Подробнее...
|
|
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. |
|
Подробнее...
|
|
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page: |
|
Подробнее...
|
B.A. History of the software
Python was created in the early 1990s by Guido van Rossum at Stichting Mathematisch Centrum (CWI) in the Netherlands as a successor of a language called ABC. Guido is Python's principal author, although it includes many contributions from others. The last version released from CWI was Python 1.2. In 1995, Guido continued his work on Python at the Corporation for National Research Initiatives (CNRI) in Reston, Virginia where he released several versions of the software. Python 1.6 was the last of the versions released by CNRI. In 2000, Guido and the Python core development team moved to BeOpen.com to form the BeOpen PythonLabs team. Python 2.0 was the first and only release from BeOpen.com. |
|
Подробнее...
|
B.B.1. PSF license agreement
- This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and the Individual or Organization ("Licensee") accessing and otherwise using Python 2.1.1 software in source or binary form and its associated documentation.
|
|
Подробнее...
|
|
|
|
|
|
|
|
|
|
кухонные плиты газовые / / обслуговування систем відеоспостереження
|