Multiparadigm programming language – Python
Информатика, кибернетика и программирование
Multiprdigm progrmming lnguge Python.1 Python is generlpurpose progrmming lnguge tht blends procedurl functionl nd objectoriented prdigms. Python is powerful multiprdigm computer progrmming lnguge optimized for progrmmer productivity code redbility nd softwre qulity. Python is populr open source progrmming lnguge used for both stndlone progrms nd scripting pplictions in wide vriety of domins.
Lecture 13. Multiparadigm programming language Python.1
Python is a general-purpose programming language that blends procedural, functional, and object-oriented paradigms. Python is a powerful multiparadigm computer programming language, optimized for programmer productivity, code readability, and software quality.
Python is a popular open source programming language used for both standalone programs and scripting applications in a wide variety of domains. It is free, portable, powerful, and is both relatively easy and remarkably fun to use. Programmers from every corner of the software industry have found Pythons focus on developer productivity and software quality to be a strategic advantage in projects both large and small.
13.1 The Python 2.X and 3.X Lines
In 2009, Python had just become available in two flavors:
While 3.X was largely the same language, it ran almost no code written for prior releases:
The mutation of print from statement to function alone, aesthetically sound as it may be, broke nearly every Python program ever written. And strategic potential aside, 3.Xs mandatory Unicode and class models and ubiquitous generators made for a different programming experience.
Although many viewed Python 3.X as both an improvement and the future of Python, Python 2.X was still very widely used and was to be supported in parallel with Python 3.X for years to come. The majority of Python code in use was 2.X, and migration to 3.X seemed to be shaping up to be a slow process.
In 2013, Python has moved on to versions 3.3 and 2.7. In fact, Python is now a dual-version world, with many users running both 2.X and 3.X according to their software goals and dependencies. And for many newcomers, the choice between 2.X and 3.X remains one of existing software versus the languages cutting edge. Although many major Python packages have been ported to 3.X, many others are still 2.X-only today.
13.2 The language characteristics
The primary factors cited by Python users seem to be these: software quality, developer productivity, program portability, support libraries, component integration, enjoyment.
Software quality. For many, Pythons focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Python code is designed to be readable, and hence reusable and maintainablemuch more so than traditional scripting languages. The uniformity of Python code makes it easy to understand, even if you did not write it. In addition, Python has deep support for more advanced software reuse mechanisms, such as object-oriented (OO) and function programming.
Developer productivity. Python boosts developer productivity many times beyond compiled or statically typed languages such as C, C++, and Java. Python code is typically one-third to one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps required by some other tools, further boosting programmer speed.
Program portability. Most Python programs run unchanged on all major computer platforms. Porting Python code between Linux and Windows, for example, is usually just a matter of copying a scripts code between machines. Moreover, Python offers multiple options for coding portable graphical user interfaces, database access programs, web-based systems, and more. Even operating system interfaces, including program launches and directory processing, are as portable in Python as they can possibly be.
Support libraries. Python comes with a large collection of prebuilt and portable functionality, known as the standard library. This library supports an array of application-level programming tasks, from text pattern matching to network scripting. In addition, Python can be extended with both homegrown libraries and a vast collection of third-party application support software. Pythons third-party domain offers tools for website construction, numeric programming, serial port access, game development, and much more. The NumPy extension, for instance, has been described as a free and more powerful equivalent to the Matlab numeric programming system.
Component integration. Python scripts can easily communicate with other parts of an application, using a variety of integration mechanisms. Such integrations allow Python to be used as a product customization and extension tool. Today, Python code can invoke C and C++ libraries, can be called from C and C++ programs, can integrate with Java and .NET components, can communicate over frameworks such as COM and Silverlight, can interface with devices over serial ports, and can interact over networks with interfaces like SOAP, XML-RPC, and CORBA. It is not a standalone tool.
Enjoyment. Because of Pythons ease of use and built-in toolset, it can make the act of programming more pleasure than chore. Although this may be an intangible benefit, its effect on productivity is an important asset.
There is one significant universal downside to Python: its execution speed may not always be as fast as that of fully compiled and lower-level languages such as C and C++.
The standard implementations of Python today compile (i.e., translate) source code statements to an intermediate format known as byte code and then interpret the byte code. Byte code provides portability, as it is a platform-independent format. However, because Python is not normally compiled all the way down to binary machine code (e.g., instructions for an Intel chip), some programs will run more slowly in Python than in a fully compiled language like C.
13.3 Python user base
There are roughly 1 million Python users around the world today (plus or minus a few). This estimate is based on various statistics, like download rates, web statistics, and developer surveys. Because Python is open source, a more exact count is difficultthere are no license registrations to tally. Moreover, Python is automatically included with Linux distributions, Macintosh computers, and a wide range of products and hardware, further clouding the user-base picture.
Python is also being applied in real revenue-generating products by real companies. For instance, among the generally known Python user base:
• Google makes extensive use of Python in its web search systems.
• The popular YouTube video sharing service is largely written in Python.
• The Dropbox storage service codes both its server and desktop client software primarily in Python.
• The Raspberry Pi single-board computer promotes Python as its educational language.
• EVE Online, a massively multiplayer online game (MMOG) by CCP Games, uses Python broadly.
• The widespread BitTorrent peer-to-peer file sharing system began its life as a Python program.
• Industrial Light & Magic, Pixar, and others use Python in the production of animated movies.
• ESRI uses Python as an end-user customization tool for its popular GIS mapping products.
• Googles App Engine web development framework uses Python as an application language.
• The IronPort email server product uses more than 1 million lines of Python code to do its job.
• Maya, a powerful integrated 3D modeling and animation system, provides a Python scripting API.
• The NSA uses Python for cryptography and intelligence analysis.
• iRobot uses Python to develop commercial and military robotic devices.
• Intel, Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware testing.
• JPMorgan Chase, UBS, Getco, and Citadel apply Python to financial market forecasting.
• NASA, Los Alamos, Fermilab, JPL, and others use Python for scientific programming tasks.
13.4 Python application domains
Some of Pythons most common applications today, as well as tools used in each domain, include the following.
Pythons built-in interfaces to operating-system services make it ideal for writing portable, maintainable system-administration tools and utilities (sometimes called shell tools). Python programs can search files and directory trees, launch other programs, do parallel processing with processes and threads, and so on. Pythons standard library comes with POSIX bindings and support for all the usual OS tools: environment variables, files, sockets, pipes, processes, multiple threads, regular expression pattern matching, command-line arguments, standard stream interfaces, shell-command launchers, filename expansion, zip file utilities, XML and JSON parsers, CSV file handlers, and more. In addition, the bulk of Pythons system interfaces are designed to be portable; for example, a script that copies directory trees typically runs unchanged on all major Python platforms. The Stackless Python implementation, described in Chapter 2 and used by EVE Online, also offers advanced solutions to multiprocessing requirements.
Pythons simplicity and rapid turnaround also make it a good match for graphical user interface programming on the desktop. Python comes with a standard object-oriented interface to the Tk GUI API called tkinter (Tkinter in 2.X) that allows Python programs to implement portable GUIs with a native look and feel. Python/tkinter GUIs run unchanged on Microsoft Windows, X Windows (on Unix and Linux), and the Mac OS (both Classic and OS X). A free extension package, PMW, adds advanced widgets to the tkinter toolkit. In addition, the wxPython GUI API, based on a C++ library, offers an alternative toolkit for constructing portable GUIs in Python. Higher-level toolkits such as Dabo are built on top of base APIs such as wxPython and tkinter. With the proper library, you can also use GUI support in other toolkits in Python, such as Qt with PyQt, GTK with PyGTK, MFC with PyWin32, .NET with IronPython, and Swing with Jython or JPype. For applications that run in web browsers or have simple interface requirements, both Jython and Python web frameworks and server-side CGI scripts, described in the next section, provide additional user interface options.
Pythons ability to be extended by and embedded in C and C++ systems makes it useful as a flexible glue language for scripting the behavior of other systems and components. For instance, integrating a C library into Python enables Python to test and launch the librarys components, and embedding Python in a product enables onsite customizations to be coded without having to recompile the entire product (or ship its source code at all). Tools such as the SWIG and SIP code generators can automate much of the work needed to link compiled components into Python for use in scripts, and the Cython system allows coders to mix Python and C-like code. Larger frameworks, such as Pythons COM support on Windows, the Jython Java-based implementation, and the IronPython .NET-based implementation provide alternative ways to script components. On Windows, for example, Python scripts can use frameworks to script Word and Excel, access Silverlight, and much more.
For traditional database demands, there are Python interfaces to all commonly used relational database systemsSybase, Oracle, Informix, ODBC, MySQL, PostgreSQL, SQLite, and more. The Python world has also defined a portable database API for accessing SQL database systems from Python scripts, which looks the same on a variety of underlying database systems. For instance, because the vendor interfaces implement the portable API, a script written to work with the free MySQL system will work largely unchanged on other systems (such as Oracle); all you generally have to do is replace the underlying vendor interface. The in-process SQLite embedded SQL database engine is a standard part of Python itself since 2.5, supporting both prototyping and basic program storage needs. In the non-SQL department, Pythons standard pickle module provides a simple object persistence systemit allows programs to easily save and restore entire Python objects to files and file-like objects. On the Web, youll also find third-party open source systems named ZODB and Durus that provide complete object-oriented database systems for Python scripts; others, such as SQLObject and SQLAlchemy, that implement object relational mappers (ORMs), which graft Pythons class model onto relational tables; and PyMongo, an interface to MongoDB, a high-performance, non-SQL, open source JSON-style document database, which stores data in structures very similar to Pythons own lists and dictionaries, and whose text may be parsed and created with Pythons own standard library json module. Still other systems offer more specialized ways to store data, including the datastore in Googles App Engine, which models data with Python classes and provides extensive scalability, as well as additional emerging cloud storage options such as Azure, Pi-Cloud, OpenStack, and Stackato.
To Python programs, components written in Python and C look the same. Because of this, its possible to prototype systems in Python initially, and then move selected components to a compiled language such as C or C++ for delivery. Unlike some prototyping tools, Python doesnt require a complete rewrite once the prototype has solidified. Parts of the system that dont require the efficiency of a language such as C++ can remain coded in Python for ease of maintenance and use.
Numeric and Scientific Programming.
Python is also heavily used in numeric programminga domain that would not traditionally have been considered to be in the scope of scripting languages, but has grown to become one of Pythons most compelling use cases. Prominent here, the NumPy high-performance numeric programming extension for Python mentioned earlier includes such advanced tools as an array object, interfaces to standard mathematical libraries, and much more. By integrating Python with numeric routines coded in a compiled language for speed, NumPy turns Python into a sophisticated yet easy-to-use numeric programming tool that can often replace existing code written in traditional compiled languages such as FORTRAN or C++. Additional numeric tools for Python support animation, 3D visualization, parallel processing, and so on. The popular SciPy and ScientificPython extensions, for example, provide additional libraries of scientific programming tools and use NumPy as a core component. The PyPy implementation of Python has also gained traction in the numeric domain, in part because heavily algorithmic code of the sort thats common in this domain can run dramatically faster in PyPyoften 10X to 100X quicker.
And More: Gaming, Images, Data Mining, Robots, Excel...
Python is commonly applied in more domains than can be covered here. For example, youll find tools that allow you to use Python to do:
• Game programming and multimedia with pygame, cgkit, pyglet, PySoy, Panda3D, and others
• Serial port communication on Windows, Linux, and more with the PySerial extension
• Image processing with PIL and its newer Pillow fork, PyOpenGL, Blender, Maya, and more
• Robot control programming with the PyRo toolkit
• Natural language analysis with the NLTK package
• Instrumentation on the Raspberry Pi and Arduino boards
• Mobile computing with ports of Python to the Google Android and Apple iOS platforms
• Excel spreadsheet function and macro programming with the PyXLL or DataNitro add-ins
• Media file content and metadata tag processing with PyMedia, ID3, PIL/Pillow, and more
Artificial intelligence with the PyBrain neural net library and the Milk machine learning toolkit
• Expert system programming with PyCLIPS, Pyke, Pyrolog, and pyDatalog
• Network monitoring with zenoss, written in and customized with Python
• Python-scripted design and modeling with PythonCAD, PythonOCC, FreeCAD, and others
• Document processing and generation with ReportLab, Sphinx, Cheetah, PyPDF, and so on
• Data visualization with Mayavi, matplotlib, VTK, VPython, and more
• XML parsing with the xml library package, the xmlrpclib module, and third-party extensions
• JSON and CSV file processing with the json and csv modules
13.5 How Python Runs Programs
Python is a software package called an interpreter. An interpreter is a kind of program that executes other programs. When you write a Python program, the Python interpreter reads your program and carries out the instructions it contains. In effect, the interpreter is a layer of software logic between your code and the computer hardware on your machine.
When the Python package is installed on your machine, it generates a number of componentsminimally, an interpreter and a support library. Depending on how you use it, the Python interpreter may take the form of an executable program, or a set of libraries linked into another program. Depending on which flavor of Python you run, the interpreter itself may be implemented as a C program, a set of Java classes, or something else. Whatever form it takes, the Python code you write must always be run by this interpreter. And to enable that, you must install a Python interpreter on your computer.
Program Execution. What it means to write and run a Python script depends on whether you look at these tasks as a programmer, or as a Python interpreter. Both views offer important perspectives on Python programming.
The Programmers View. In its simplest form, a Python program is just a text file containing Python statements. For example, the following file, named prog1.py, is one of the simplest Python scripts, but it passes for a fully functional Python program:
print(2 ** 100)
This file contains two Python print statements, which simply print a string (the text in quotes) and a numeric expression result (2 to the power 100) to the output stream. After youve typed these statements into a text file, you must tell Python to execute the filewhich simply means to run all the statements in the file from top to bottom, one after another. As youll see in the next chapter, you can launch Python program files by shell command lines, by clicking their icons, from within IDEs, and with other standard techniques. If all goes well, when you execute the file, youll see the results of the two print statements show up somewhere on your computerby default, usually in the same window you were in when you ran the program:
Pythons View. When you instruct Python to run your script, there are a few steps that Python carries out before your code actually starts crunching away. Specifically, its first compiled to something called “byte code” and then routed to something called a “virtual machine.” Internally, and almost completely hidden from you, when you execute a program Python first compiles your source code (the statements in your file) into a format known as byte code. Compilation is simply a translation step, and byte code is a lower-level, platform-independent representation of your source code. Roughly, Python translates each of your source statements into a group of byte code instructions by decomposing them into individual steps. This byte code translation is performed to speed execution byte code can be run much more quickly than the original source code statements in your text file. If the Python process has write access on your machine, it will store the byte code of your programs in files that end with a .pyc extension (“.pyc” means compiled “.py” source). Prior to Python 3.2, you will see these files show up on your computer after youve run a few programs alongside the corresponding source code filesthat is, in the same directories. For instance, youll notice a prog1.pyc after importing a script.py.
Once your program has been compiled to byte code (or the byte code has been loaded from existing .pyc files), it is shipped off for execution to something generally known as the Python Virtual Machine (PVM). The PVM is just a big code loop that iterates through your byte code instructions, one by one, to carry out their operations. The PVM is the runtime engine of Python; its always present as part of the Python system, and its the component that truly runs your scripts. Technically, its just the last step of what is called the “Python interpreter.”
13.6 Python Implementation Alternatives
There are at least five implementations of the Python languageCPython, Jython, IronPython, Stackless, and PyPy. CPython is the standard implementation, All the other Python implementations have specific purposes and roles. All implement the same Python language but execute programs in different ways.
CPython: The standard. The original, and standard, implementation of Python is usually called CPython when you want to contrast it with the other options (and just plain “Python” otherwise). This name comes from the fact that it is coded in portable ANSI C language code.
Jython: Python for Java. The Jython system (originally known as JPython) is an alternative implementation of the Python language, targeted for integration with the Java programming language. Jython consists of Java classes that compile Python source code to Java byte code and then route the resulting byte code to the Java Virtual Machine (JVM).
IronPython: Python for .NET. A third implementation of Python, and newer than both CPython and Jython, IronPython is designed to allow Python programs to integrate with applications coded to work with Microsofts .NET Framework for Windows
Stackless: Python for concurrency. the Stackless Python system is an enhanced version and reimplementation of the standard CPython language oriented toward concurrency.
PyPy: Python for speed. The PyPy system is another standard CPython reimplementation, focused on performance. It provides a fast Python implementation with a JIT (just-in-time) compiler, provides tools for a “sandbox” model that can run untrusted code in a secure environ- ment, and by default includes support for the prior sections Stackless Python systems and its microthreads to support massive concurrency.
1 Mark Lutz. Learning Python. Fifth Edition. OReilly Media Inc. 2013.
А также другие работы, которые могут Вас заинтересовать
|35576.||Проектирование и эксплуатация газо- и водоочистки||1.88 MB|
|Более того десульфурацию проводили вдувая каустическую соду в контур охлаждающей воды рис. В процессе Эрфайн можно выделить три основные стадии: охлаждения отделения пыли и обработки воды. Крупные частицы фракцией 10мкм удаляются в результате вспрыскивания распыленной циркуляционной воды в противоток отходящему газу посредством форсунок работающих на одном виде жидкости. На стадии обработки воды взвешенные твердые частицы и тяжелые металлы удаляют из сбросовых стоков данного процесса в установке обработки воды в три этапа: отделяют...|
|35577.||АНТИПРИГОЖИН. УПРАВЛЯЕМЫЙ ХАОС||1.69 MB|
|Вместо физического времени в ней использовался обратимый эрзац. Человек будучи вне времени становится богоподобным или намного ближе к квазибожественному состоянию.Ньютон же считал что вмешательство бога требуется в каждый момент времени отсюда эпигенез и гениальное предвидение И. Это вернуло прежний интерес к конструктивной роли времени.|
|35578.||Социология. Курс лекций в схемах||2.05 MB|
|Предмет и история социологии. Общество как социокультурная система. Социальные группы и общности. Массовое сознание и общественное мнение. Методология социологических исследований.|
|35579.||История Белоруссии||492 KB|
|В истории Белоруси выявлено много белых пятенБНРВКЛсоздание БССР и т.Полоцкая земля находилась на терр сев Белорусии в землях кривичейвключала в себя современную Вит обл.На границе 1314в Полоцкое княжество вошло в состав ВКЛ.В конце 13начале14 веков Туровская земля была включена в состав ВКЛ.|
|35580.||История беларускiх зямель||228.5 KB|
|Тэрмiн зясялення тэрыторыi Беларусi 40 тыс. Iндаеўрапейскi перыяд пачаўся ў бронзавым веку з часу рассялення iндаеўрапейскiх плямён на тэрыторыi Беларусi 3 2 тыс. Засяленне славянамi Беларусi адбывалася ў вынiку мiграцыi славян са сваёй прарадзiмы тэрыторыi памiж р. Славяне асiмiлiравалi балтаў i ў вынiку славянабалцкага ўзаемадзеяння ўзнiклi новыя этнiчныя супольнасцi: ва ўсходняй Еўропе больш за 15 на тэрыторыi Беларусi 3 гэта крывiчы дрыгавiчы радзiмiчы.|
|35581.||История Руси от древних времен до ХХ столетия||221 KB|
|Древние славяне - большая этническая группа: Восточные (русские, украинцы, белорусы); Западные (Чехи, Поляки); Южные (болгары, сербы, хорваты, македонцы). Соседи с севера: угро-финские племена, норманны, балты. С норманнами были напряженные отношения т.к. они промышляли грабежами, плавали во Францию, Испанию, Италию. Славяне часто платили им дань.|
|35582.||АДМИНИСТРАТИВНОЕ ПРАВО КАК ОТРАСЛЬ ПРАВА||138.5 KB|
|Административное право как отрасль современного права появилась тогда когда в правовой системе достаточное место заняли нормы закрепляющие права личности гарантии от административного произвола. Реализация в законодательстве идей естественных и неотъемлемых прав гражданина разделения властей контроля за государственной администрацией необходимое условие превращения полицейского права в административное. Административное право очень важная отрасль права так как роль государственной администрации в России очень велика.|
|35583.||Общее понятие экономической безопасности страны||97 KB|
|Понятие национальной безопасности шире понятия экономической безопасности страны оно включает оборонную экологическую энергетическую безопасность и т. Сущность экономической безопасности можно определить как такое состояние экономики и институтов власти при которых обеспечиваются гарантированная защита национальных интересов социально направленное развитие страны в целом достаточный оборонный потенциал даже при наиболее неблагоприятном условии развития внутренних и внешних процессов. Мировая практика показывает что даже при существенном...|
|35584.||Предмет и функции гражданского права||175 KB|
|Например: возможно заключение договора который предусматривает ежемесячные поставки в определенном законе если покупатель не сообщит о своем отказе от получения товара в течение какоголибо срока до начала очередного срока молчание ДА. Так общества с ограниченной или дополнительной ответственностью ассоциации и союзы действуют на основе учредительного договора и устава. Его можно рассматривать как разновидность договора простого товарищества договора о совместной деятельности хотя существует и мнение о том что это...|