This document provides an introduction and overview of the Python programming language. It discusses Python's origins, philosophy, features, and uses. Key points covered include Python's simplicity, power, object-oriented approach, and wide portability. Examples are provided of basic Python syntax and constructs like strings, lists, functions, modules, and dictionaries.
( ** Python Certification Training: https://www.edureka.co/python ** )
This Edureka PPT on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.
This document discusses various string methods in Python including upper(), lower(), capitalize(), startswith(), endswith(), strip(), split(), and join(). It provides examples of how to use each method, such as converting strings to uppercase and lowercase, checking if a string starts or ends with certain text, stripping leading and trailing characters, and splitting or joining strings.
This document discusses the structure of a C++ program. It begins by defining software and the different types. It then discusses key concepts in C++ like classes, objects, functions, and headers. It provides examples of a class declaration with private and public sections, member functions, and a main function. It also discusses practical training resources available for learning C++ including e-learning websites, e-assignments, e-content, and mobile apps.
This document discusses object-oriented programming in C++. It covers several topics related to OOP in C++ including classes, constructors, destructors, inheritance, polymorphism, and templates. The document consists of lecture slides that define key concepts and provide examples to illustrate how various OOP features work in C++.
Python is a widely used high-level programming language for general-purpose programming. Python is a simple, powerful and easy to learn the programming language. It is commonly used for Web and Internet development, Scientific and Numeric computing, Business application and Desktop GUI development etc. The basic data structures in python are lists, dictionaries, tuples, strings and sets
The document discusses object-oriented programming (OOP) concepts in C++. It defines key OOP concepts like classes, objects, encapsulation, inheritance and polymorphism. It explains that in OOP, classes encapsulate both data and functions that operate on that data. Classes define public and private sections to control access to members. The document also provides examples to demonstrate class definition, object creation, member functions and destructors.
Modules allow grouping of related functions and code into reusable files. Packages are groups of modules that provide related functionality. There are several ways to import modules and their contents using import and from statements. The document provides examples of creating modules and packages in Python and importing from them.
The document discusses different types of functions in C++ including:
1) Main functions are mandatory while other programs define additional functions. Functions are declared with a return type, name, and parameters.
2) Functions are defined with a syntax including the return type, name, parameters, and body. Functions can be called within other functions or the main function by passing values.
3) Inline functions have their code placed at the call site at compile time to avoid function call overhead. They are defined using the inline keyword before the return type for small, single line functions.
4) Functions can have default arguments which are values provided in the declaration that are used if not passed to the function. They must
( ** Python Certification Training: https://www.edureka.co/python ** )
This Edureka PPT on Tkinter tutorial covers all the basic aspects of creating and making use of your own simple Graphical User Interface (GUI) using Python. It establishes all of the concepts needed to get started with building your own user interfaces while coding in Python.
This document discusses various string methods in Python including upper(), lower(), capitalize(), startswith(), endswith(), strip(), split(), and join(). It provides examples of how to use each method, such as converting strings to uppercase and lowercase, checking if a string starts or ends with certain text, stripping leading and trailing characters, and splitting or joining strings.
This document discusses the structure of a C++ program. It begins by defining software and the different types. It then discusses key concepts in C++ like classes, objects, functions, and headers. It provides examples of a class declaration with private and public sections, member functions, and a main function. It also discusses practical training resources available for learning C++ including e-learning websites, e-assignments, e-content, and mobile apps.
This document discusses object-oriented programming in C++. It covers several topics related to OOP in C++ including classes, constructors, destructors, inheritance, polymorphism, and templates. The document consists of lecture slides that define key concepts and provide examples to illustrate how various OOP features work in C++.
Python is a widely used high-level programming language for general-purpose programming. Python is a simple, powerful and easy to learn the programming language. It is commonly used for Web and Internet development, Scientific and Numeric computing, Business application and Desktop GUI development etc. The basic data structures in python are lists, dictionaries, tuples, strings and sets
The document discusses object-oriented programming (OOP) concepts in C++. It defines key OOP concepts like classes, objects, encapsulation, inheritance and polymorphism. It explains that in OOP, classes encapsulate both data and functions that operate on that data. Classes define public and private sections to control access to members. The document also provides examples to demonstrate class definition, object creation, member functions and destructors.
Modules allow grouping of related functions and code into reusable files. Packages are groups of modules that provide related functionality. There are several ways to import modules and their contents using import and from statements. The document provides examples of creating modules and packages in Python and importing from them.
The document discusses different types of functions in C++ including:
1) Main functions are mandatory while other programs define additional functions. Functions are declared with a return type, name, and parameters.
2) Functions are defined with a syntax including the return type, name, parameters, and body. Functions can be called within other functions or the main function by passing values.
3) Inline functions have their code placed at the call site at compile time to avoid function call overhead. They are defined using the inline keyword before the return type for small, single line functions.
4) Functions can have default arguments which are values provided in the declaration that are used if not passed to the function. They must
Variables & Data Types In Python | EdurekaEdureka!
YouTube Link: https://youtu.be/6yrsX752CWk
(** Python Certification Training: https://www.edureka.co/python **)
This Edureka PPT on 'Variables and Data Types in Python' will help you establish a foothold on Python by helping you learn basic concepts like variables and data types. Below are the topics covered in this PPT:
Introduction To Python
Applications Of Python
Variable Declaration
Variable Data Types
Type Conversion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Regular expressions are a powerful tool for searching, matching, and parsing text patterns. They allow complex text patterns to be matched with a standardized syntax. All modern programming languages include regular expression libraries. Regular expressions can be used to search strings, replace parts of strings, split strings, and find all occurrences of a pattern in a string. They are useful for tasks like validating formats, parsing text, and finding/replacing text. This document provides examples of common regular expression patterns and methods for using regular expressions in Python.
This document provides an overview of object-oriented programming concepts using C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. It also covers C++ specific topics like functions, arrays, strings, modular programming, and classes and objects in C++. The document is intended to introduce the reader to the fundamentals of OOP using C++.
String literals in python are surrounded by either single quotation marks, or double quotation marks. Strings can be output to screen using the print function. For example: print("hello"). Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
The document discusses GUI technologies in Python. It covers Tkinter, which is the standard GUI library in Python. Tkinter can be used to create desktop applications and provides widgets like labels, buttons, entries and frames. It also discusses how to create windows, add widgets, handle events and create a simple calculator application as an example.
The document discusses input/output streams in Java. It covers:
- Different types of data storage including transient RAM and persistent storage like disks.
- I/O sources and destinations like consoles, disks, networks etc. and how streams represent sequential bytes to abstract I/O details.
- Common Java I/O stream classes like FileReader, FileWriter, InputStream and OutputStream for reading/writing text and binary data from files.
- Using File class to represent files and directories with methods to check attributes, read content and manipulate files.
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects.
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
This document discusses Python namespaces and modules. It explains that namespaces prevent name conflicts and modules are the basic unit of code reuse. Functions, classes, and modules each have their own namespace. Importing modules adds their names to the global namespace. The document recommends importing modules using 'import' to avoid potential name conflicts or namespace pollution. It also describes how scopes resolve which definition to use when the same name is defined in multiple scopes.
The document discusses arrays in Java, including how to declare and initialize one-dimensional and two-dimensional arrays, access array elements, pass arrays as parameters, and sort and search arrays. It also covers arrays of objects and examples of using arrays to store student data and daily temperature readings from multiple cities over multiple days.
All data values in Python are encapsulated in relevant object classes. Everything in Python is an object and every object has an identity, a type, and a value. Like another object-oriented language such as Java or C++, there are several data types which are built into Python. Extension modules which are written in C, Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The value of some objects can be changed. Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are created) are called immutable.
The document provides an introduction to Python programming. It discusses installing and running Python, basic Python syntax like variables, data types, conditionals, and functions. It emphasizes that Python uses references rather than copying values, so assigning one variable to another causes both to refer to the same object.
A cluster is an accumulation of factors of a similar sort that are alluded to through a typical name. A particular component in a cluster is gotten to by a file. In C, all clusters comprise of coterminous memory areas.
This document contains 14 C program examples that print various pyramid patterns. The programs demonstrate basic C programming concepts like loops, conditional statements, functions and demonstrate printing patterns using characters, numbers or both. Each program includes the code, comments on purpose and author. The output displayed below each program code verifies the pattern printed. Overall the document serves as a learning resource for basic C programming and pattern printing techniques.
The document discusses various primitive data types including integer, floating point, decimal, boolean, character, and string types. It covers the implementation and design considerations of these types in different programming languages such as C, C++, Java, and C#. Enumeration types are also introduced as user-defined ordinal types.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
This document discusses Python functions. It defines a function as a block of code that performs a specific task. Functions help break programs into smaller, modular chunks. The document explains how to define functions using the def keyword, how to call functions, and how functions can take arguments. It also covers default arguments, keyword arguments, arbitrary arguments, recursion, anonymous functions, and provides examples of each.
This document discusses function call by value and reference in C programming. It provides examples of swapping integer values using each method. Call by value passes the actual value of an argument, so changes made to parameters inside the function do not affect the argument. Call by reference passes the address of an argument, allowing the function to access and modify the original argument value. The key differences are that call by value uses general variables as arguments while call by reference uses pointer variables, and only call by reference reflects changes to formal parameters in the actual parameters.
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
Pointer is a variable that stores the memory address of another variable. It allows dynamic memory allocation and access of memory locations. There are three ways to pass arguments to functions in C++ - pass by value, pass by reference, and pass by pointer. Pass by value copies the value, pass by reference copies the address, and pass by pointer passes the address of the argument. Pointers can also point to arrays or strings to access elements. Arrays of pointers can store multiple strings. References are alternative names for existing variables and any changes made using the reference affect the original variable. Functions can return pointers or references.
Download this Presentation for free from www.ecti.co.in/downloads.html
No SIGN UP REQUIRED.
C Programming Training PPTs / PDFs for free.
Download free C Programming study material. Learn C Programming for free in 2 hours.
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:
https://www.youtube.com/watch?v=N6cQRG5oEAY
Variables & Data Types In Python | EdurekaEdureka!
YouTube Link: https://youtu.be/6yrsX752CWk
(** Python Certification Training: https://www.edureka.co/python **)
This Edureka PPT on 'Variables and Data Types in Python' will help you establish a foothold on Python by helping you learn basic concepts like variables and data types. Below are the topics covered in this PPT:
Introduction To Python
Applications Of Python
Variable Declaration
Variable Data Types
Type Conversion
Python Tutorial Playlist: https://goo.gl/WsBpKe
Blog Series: http://bit.ly/2sqmP4s
Follow us to never miss an update in the future.
YouTube: https://www.youtube.com/user/edurekaIN
Instagram: https://www.instagram.com/edureka_learning/
Facebook: https://www.facebook.com/edurekaIN/
Twitter: https://twitter.com/edurekain
LinkedIn: https://www.linkedin.com/company/edureka
Regular expressions are a powerful tool for searching, matching, and parsing text patterns. They allow complex text patterns to be matched with a standardized syntax. All modern programming languages include regular expression libraries. Regular expressions can be used to search strings, replace parts of strings, split strings, and find all occurrences of a pattern in a string. They are useful for tasks like validating formats, parsing text, and finding/replacing text. This document provides examples of common regular expression patterns and methods for using regular expressions in Python.
This document provides an overview of object-oriented programming concepts using C++. It discusses key OOP concepts like objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding. It also covers C++ specific topics like functions, arrays, strings, modular programming, and classes and objects in C++. The document is intended to introduce the reader to the fundamentals of OOP using C++.
String literals in python are surrounded by either single quotation marks, or double quotation marks. Strings can be output to screen using the print function. For example: print("hello"). Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters.
The document discusses GUI technologies in Python. It covers Tkinter, which is the standard GUI library in Python. Tkinter can be used to create desktop applications and provides widgets like labels, buttons, entries and frames. It also discusses how to create windows, add widgets, handle events and create a simple calculator application as an example.
The document discusses input/output streams in Java. It covers:
- Different types of data storage including transient RAM and persistent storage like disks.
- I/O sources and destinations like consoles, disks, networks etc. and how streams represent sequential bytes to abstract I/O details.
- Common Java I/O stream classes like FileReader, FileWriter, InputStream and OutputStream for reading/writing text and binary data from files.
- Using File class to represent files and directories with methods to check attributes, read content and manipulate files.
What is the DOM?
The DOM is a W3C (World Wide Web Consortium) standard.
The DOM defines a standard for accessing documents:
"The W3C Document Object Model (DOM) is a platform and language-neutral interface that allows programs and scripts to dynamically access and update the content, structure, and style of a document."
The W3C DOM standard is separated into 3 different parts:
Core DOM - standard model for all document types
XML DOM - standard model for XML documents
HTML DOM - standard model for HTML documents
The HTML DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model is constructed as a tree of Objects.
With the HTML DOM, JavaScript can access and change all the elements of an HTML document.
This document discusses Python namespaces and modules. It explains that namespaces prevent name conflicts and modules are the basic unit of code reuse. Functions, classes, and modules each have their own namespace. Importing modules adds their names to the global namespace. The document recommends importing modules using 'import' to avoid potential name conflicts or namespace pollution. It also describes how scopes resolve which definition to use when the same name is defined in multiple scopes.
The document discusses arrays in Java, including how to declare and initialize one-dimensional and two-dimensional arrays, access array elements, pass arrays as parameters, and sort and search arrays. It also covers arrays of objects and examples of using arrays to store student data and daily temperature readings from multiple cities over multiple days.
All data values in Python are encapsulated in relevant object classes. Everything in Python is an object and every object has an identity, a type, and a value. Like another object-oriented language such as Java or C++, there are several data types which are built into Python. Extension modules which are written in C, Java, or other languages can define additional types.
To determine a variable's type in Python you can use the type() function. The value of some objects can be changed. Objects whose value can be changed are called mutable and objects whose value is unchangeable (once they are created) are called immutable.
The document provides an introduction to Python programming. It discusses installing and running Python, basic Python syntax like variables, data types, conditionals, and functions. It emphasizes that Python uses references rather than copying values, so assigning one variable to another causes both to refer to the same object.
A cluster is an accumulation of factors of a similar sort that are alluded to through a typical name. A particular component in a cluster is gotten to by a file. In C, all clusters comprise of coterminous memory areas.
This document contains 14 C program examples that print various pyramid patterns. The programs demonstrate basic C programming concepts like loops, conditional statements, functions and demonstrate printing patterns using characters, numbers or both. Each program includes the code, comments on purpose and author. The output displayed below each program code verifies the pattern printed. Overall the document serves as a learning resource for basic C programming and pattern printing techniques.
The document discusses various primitive data types including integer, floating point, decimal, boolean, character, and string types. It covers the implementation and design considerations of these types in different programming languages such as C, C++, Java, and C#. Enumeration types are also introduced as user-defined ordinal types.
Object oriented programming with pythonArslan Arshad
A short intro to how Object Oriented Paradigm work in Python Programming language. This presentation created for beginner like bachelor student of Computer Science.
This document discusses Python functions. It defines a function as a block of code that performs a specific task. Functions help break programs into smaller, modular chunks. The document explains how to define functions using the def keyword, how to call functions, and how functions can take arguments. It also covers default arguments, keyword arguments, arbitrary arguments, recursion, anonymous functions, and provides examples of each.
This document discusses function call by value and reference in C programming. It provides examples of swapping integer values using each method. Call by value passes the actual value of an argument, so changes made to parameters inside the function do not affect the argument. Call by reference passes the address of an argument, allowing the function to access and modify the original argument value. The key differences are that call by value uses general variables as arguments while call by reference uses pointer variables, and only call by reference reflects changes to formal parameters in the actual parameters.
METHODS DESCRIPTION
copy() They copy() method returns a shallow copy of the dictionary.
clear() The clear() method removes all items from the dictionary.
pop() Removes and returns an element from a dictionary having the given key.
popitem() Removes the arbitrary key-value pair from the dictionary and returns it as tuple.
get() It is a conventional method to access a value for a key.
dictionary_name.values() returns a list of all the values available in a given dictionary.
str() Produces a printable string representation of a dictionary.
update() Adds dictionary dict2’s key-values pairs to dict
setdefault() Set dict[key]=default if key is not already in dict
keys() Returns list of dictionary dict’s keys
items() Returns a list of dict’s (key, value) tuple pairs
has_key() Returns true if key in dictionary dict, false otherwise
fromkeys() Create a new dictionary with keys from seq and values set to value.
type() Returns the type of the passed variable.
cmp() Compares elements of both dict.
Pointer is a variable that stores the memory address of another variable. It allows dynamic memory allocation and access of memory locations. There are three ways to pass arguments to functions in C++ - pass by value, pass by reference, and pass by pointer. Pass by value copies the value, pass by reference copies the address, and pass by pointer passes the address of the argument. Pointers can also point to arrays or strings to access elements. Arrays of pointers can store multiple strings. References are alternative names for existing variables and any changes made using the reference affect the original variable. Functions can return pointers or references.
Download this Presentation for free from www.ecti.co.in/downloads.html
No SIGN UP REQUIRED.
C Programming Training PPTs / PDFs for free.
Download free C Programming study material. Learn C Programming for free in 2 hours.
The basics of Python are rather straightforward. In a few minutes you can learn most of the syntax. There are some gotchas along the way that might appear tricky. This talk is meant to bring programmers up to speed with Python. They should be able to read and write Python.
This presentation is a part of the COP2271C college level course taught at the Florida Polytechnic University located in Lakeland Florida. The purpose of this course is to introduce Freshmen students to both the process of software development and to the Python language.
The course is one semester in length and meets for 2 hours twice a week. The Instructor is Dr. Jim Anderson.
A video of Dr. Anderson using these slides is available on YouTube at:
https://www.youtube.com/watch?v=N6cQRG5oEAY
This document provides an overview of how to build and test Python modules for use with Zabbix's ZLM-Cython framework. It discusses the necessary Python knowledge, module locations and structure, testing modules locally, creating Zabbix items to retrieve metrics from modules, and handling exceptions. Future sections will cover passing parameters to modules and using the ZLM-Python context object to share data between processes. The goal is to help readers understand how to develop effective custom monitoring modules for Zabbix using Python.
The document provides an overview of Python's typing module introduced in Python 3.5. It discusses the benefits of type hinting, including better documentation, finding bugs, and standardization. It demonstrates applying type hints to a simple function and running a type checker. Tips are provided for gradually adding type hints to improve code quality without changing functionality.
Python modules allow programmers to split code into multiple files for easier maintenance. A module is simply a Python file with a .py extension. The import statement is used to include modules. Modules can be organized into packages, which are directories containing an __init__.py file. Popular third party modules like ElementTree, Psyco, EasyGUI, SQLObject, and py.test make Python even more powerful.
Python AST / Николай Карелин / VPI Development Center [Python Meetup 27.03.15]Python Meetup
Python AST: между исходным текстом и байт-кодом / Николай Карелин / Системный архитектор VPI Development Center
Николай познакомит слушателей с деталями устройства Python AST и, в частности, расскажет некоторые интересные факты о работе диалекта Hy.
Python Meetup - встречи минского сообщества любителей языка программирования Python.
Присоединяйся к нам!
Мы в twitter: https://twitter.com/pythonminsk
Мы на youtube: http://www.youtube.com/pythonMinsk
Мы на slideshare: http://www.slideshare.net/MinskPythonMeetup
El documento describe varias características y tecnologías de Java como la entrada y salida de datos, serialización, Java Foundation Classes, Java 2D, Java Media Framework, Java Beans y Java Native Interface. La entrada y salida de datos en Java se basa en flujos de datos. La serialización convierte objetos en secuencias de bytes para almacenarlos. Java Foundation Classes proporciona herramientas gráficas portables.
Introdução à linguagem de programação PythonCarlos Schults
O documento apresenta uma introdução à linguagem de programação Python. Ele discute a história e características da linguagem, incluindo sintaxe, variáveis, entrada de dados, decisões, listas, repetição, matemática e strings. O documento também fornece links úteis para recursos adicionais sobre Python.
A palestra abordará como foi criado o CartolaFC, a escolha da sua arquitetura, como foi o processo de desenvolvimento, e o dia a dia de trabalho na globo.com.
Pivotal Data Labs - Technology and Tools in our Data Scientist's Arsenal Srivatsan Ramanujam
These slides give an overview of the technology and the tools used by Data Scientists at Pivotal Data Labs. This includes Procedural Languages like PL/Python, PL/R, PL/Java, PL/Perl and the parallel, in-database machine learning library MADlib. The slides also highlight the power and flexibility of the Pivotal platform from embracing open source libraries in Python, R or Java to using new computing paradigms such as Spark on Pivotal HD.
Palestra Apresentando Python e Suas AplicaçõesMarcos Thomaz
Python é uma linguagem de programação de alto nível, interpretada e interativa. Foi criada por Guido van Rossum no início dos anos 1990 e atualmente está na versão 3.4.1. Pode ser usada para diversos fins como desenvolvimento web, ciência, inteligência artificial, entre outros. A linguagem é orientada a objetos, dinâmica e fortemente tipada.
Palestra realizada no dia 10/02/2011 no X Encontro do Grupo de Usuários de Python na Livraria Cultura (Recife -Pernambuco). Palestra com o título: "Conhecendo Python e por que ela importa ? "
Lecture presented at February 09th at X Meeting of Pernambuco Python User Group at Livraria Cultura (Recife - Pernambuco - Brazil) with the title: ' Meeting Python and why does it care ? "
O documento apresenta uma palestra sobre o uso de Python e Django na Globo.com. Resume os principais pontos como: 1) a Globo.com usa Python/Django há 11 anos com metodologias ágeis; 2) antes usava Java/Vignette com problemas, agora tem desenvolvimento orientado a testes; 3) Django ajuda a construir aplicações, mas não é perfeito e às vezes é preciso ignorá-lo.
Este documento apresenta uma introdução à orientação a objetos em Python. Resume os principais tópicos abordados:
1) Python suporta herança múltipla, sobrecarga de operadores e tipagem dinâmica, mas não obriga a criação de classes;
2) Em Python, tudo é objeto e variáveis podem ser associadas a objetos de qualquer tipo em tempo de execução (tipagem dinâmica forte);
3) Classes devem herdar de object e métodos devem declarar self como primeiro parâmetro; propriedades permitem encaps
Python es un lenguaje de programación dinámico e interpretado que ofrece tipado dinámico, fuerte tipado, flexibilidad y portabilidad. Sus principales características incluyen una sintaxis limpia y legible similar al pseudocódigo, una amplia biblioteca estándar y ser multiplataforma. Python se puede utilizar para el desarrollo web, bases de datos, software, juegos, bioinformática, física y educación.
The Agenda for the Webinar:
1. Introduction to Python.
2. Python and Big Data.
3. Python and Data Science.
4. Key features of Python and their usage in Business Analytics.
5. Business Analytics with Python – Real world Use Cases.
The document discusses functions, modules, and how to modularize Python programs. It provides examples of defining functions, using parameters, returning values, and function scope. It also discusses creating modules, importing modules, and the difference between running a Python file as a module versus running it as the main script using the __name__ == "__main__" check. The key points are that functions help break programs into reusable and readable components, modules further help organize code, and the __name__ check allows code to run differently depending on how it is imported or run directly.
Python is a widely used general purpose programming language that was created in the late 1980s by Guido van Rossum. It emphasizes code readability and has a large standard library. It supports multiple programming paradigms like object oriented, imperative, and functional programming. Compared to other languages, Python programs are typically shorter than equivalent programs in languages like Java due to features like dynamic typing.
Python is a general purpose programming language that can be used for both programming and scripting. It was created in the 1990s by Guido van Rossum who named it after the Monty Python comedy troupe. People use Python for a variety of tasks due to its readability, object-oriented capabilities, extensive libraries, and ability to integrate with other languages. To run Python code, it must first be compiled into bytecode which is then interpreted by the Python virtual machine.
Python classes in mumbai
best Python classes in mumbai with job assistance.
our features are:
expert guidance by it industry professionals
lowest fees of 5000
practical exposure to handle projects
well equiped lab
after course resume writing guidance
This document provides an introduction and overview of the Python programming language. It describes Python's origins, philosophy, features, and uses. Key points covered include Python's support for rapid development, object-oriented programming, embedding and extending with C, and its portability across platforms. Examples of Python code are provided to illustrate concepts like modules, functions, control flow, and data types.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins and philosophy of being coherent, powerful, and easy to read and maintain. Key features of Python mentioned include rapid development, object orientation, embedding in C, dynamic typing, exceptions, and built-in interfaces to external services. The document also outlines some common uses of Python and examples of basic Python code structure, variables, operations, control flow, functions, and data types like lists, tuples, and dictionaries.
This document provides an overview of the Python programming language. It discusses that Python is a popular, object-oriented scripting language that emphasizes code readability. The document summarizes key Python features such as rapid development, automatic memory management, object-oriented programming, and embedding/extending with C. It also outlines common uses of Python and when it may not be suitable.
This document provides an overview of the Python programming language. It discusses Python's origins, philosophy, features, and uses. Key points include that Python is an interpreted, object-oriented scripting language designed for readability and rapid development. It has automatic memory management, high-level data types, and built-in interfaces for tasks like GUI development. The document also covers Python programming basics like modules, functions, control flow, and data structures like lists, tuples, and dictionaries.
This document provides an overview of the Python programming language. It discusses Python's origins, philosophy, and features such as rapid development, object orientation, embedding in C, dynamic loading of modules, universal objects, and built-in interfaces to external services. The document also covers Python basics like data types, control flow, functions, modules, and exceptions. It provides examples of Python code and describes how to use Python in areas like shell tools, system administration, GUIs, databases, and distributed programming.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins and influences from other languages. Key features of Python mentioned include its rapid development cycle, automatic memory management, object-oriented programming support, and ability to be embedded in C/C++. The document also gives examples of common Python constructs like functions, control flow, lists, dictionaries, and modules.
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
C++ STL is a collection of containers and algorithms that provide common programming tasks. It includes data structures like vector, set, map as well as sorting and searching algorithms. Using STL containers makes code shorter, faster and more error-free compared to manually writing these routines. STL is important for learning advanced C++ concepts like graphs and algorithms.
This document provides an overview of the Python programming language. It begins with an introduction to why Python is a good choice. It then outlines a tutorial on Python's basic types like numbers, strings, lists, dictionaries, variables, control structures, functions, classes, modules, exceptions, and files. It encourages downloading the latest Python version and using the interactive shell or IDLE to experiment. The bulk of the document then provides details on Python's core concepts like numbers, strings, lists, dictionaries, tuples, variables, control structures, functions, classes, modules, exceptions, and files. It concludes by discussing new features in Python 2.0 and 2.1.
This document provides an overview of the Python programming language. It discusses Python's history and origins, philosophy of being readable and powerful, features like dynamic typing and automatic memory management, uses for shell tools, prototyping, GUIs and more. It also covers Python syntax, modules, functions, control flow, objects and data types like lists, dictionaries and tuples.
This document provides an overview of Python fundamentals including installing Python, hidden documentation tools, data types, strings, lists, tuples, dictionaries, control flow statements, functions, classes, the datetime library, importing modules, and web2py fundamentals such as the request and response objects, templates, controllers, models, and more. Key concepts covered include Python types like strings, lists, tuples and dictionaries, control structures like if/else and for loops, functions, classes and objects, and the basics of using the web2py framework to build web applications.
This document provides an introduction to Python programming through a series of exercises. It begins with definitions of Python and why it is useful. It then covers basic Python concepts like strings, lists, loops, functions and modules. The latter half provides 5 exercises to practice these concepts, such as printing messages, removing characters, using for loops and if/else statements, writing data to a JSON file, and generating stock data from an online API. The document aims to cover Python fundamentals in 90 minutes through hands-on learning.
This document provides an overview of the Python programming language. It discusses Python's origins in 1991 and heritage from teaching languages. Key Python features include rapid development without compiling, automatic memory management, high-level data types, object-oriented programming, and embedding in C. The document also covers Python syntax, basic programming constructs like functions and control flow, data structures like lists and dictionaries, and functional programming tools.
An Overview Of Python With Functional ProgrammingAdam Getchell
This document provides an overview of the Python programming language and its capabilities for functional programming. It describes Python's attributes such as being portable, object-oriented, and supporting procedural, object-oriented, and functional programming. It also lists several popular Python modules that provide additional functionality and examples of code written in both a procedural and object-oriented style in Python. Finally, it provides examples of functional programming concepts like map, filter and reduce implemented in Python along with references for further information.
The document provides an introduction and comparison of Python and C programming languages. Some key points:
- Python is an interpreted language while C needs compilation. Python makes program development faster.
- Variables, input/output, arrays, control structures like if/else, for loops work differently in Python compared to C.
- Python uses lists instead of arrays. Lists are mutable and support slicing.
- Strings are treated as character lists in Python.
- Functions are defined using def keyword in Python.
- The document also introduces sequences (strings, tuples, lists), dictionaries, and sets in Python - their usage and operations.
This document provides an introduction and overview of the Python programming language. It discusses Python's origins in 1991 and heritage from languages like ABC, Tcl, and Perl. The document outlines Python's philosophy of coherence, power, and rapid development. Key Python features are summarized, including no compiling, dynamic typing, automatic memory management, and support for object-oriented, functional, and procedural programming. Example uses of Python like shell tools, system administration, GUIs, and web development are provided. The document also covers basic Python concepts like modules, statements, control flow, functions, strings, lists, dictionaries, and tuples.
C++ is an object-oriented programming language created by Bjarne Stroustrup in 1985 that maintains aspects of C while adding object-oriented features like classes. C++ can be used to create everything from small programs to large applications and is a powerful general-purpose language. Inheritance allows code reusability by creating new classes from existing classes or base classes, where derived classes inherit capabilities from base classes but can add their own features and refinements. Polymorphism enables objects to react differently to the same function call through virtual functions, allowing different classes that inherit from a base class to provide their own implementation of a function.
Slides for the Cluj.py meetup where we explored the inner workings of CPython, the reference implementation of Python. Includes examples of writing a C extension to Python, and introduces Cython - ultimately the sanest way of writing C extensions.
Also check out the code samples on GitHub: https://github.com/trustyou/meetups/tree/master/python-c
Adobe PDF is a universal file format that preserves all formatting and graphics of source documents regardless of the application or platform used to create it. PDF files can be opened by anyone with the free Adobe Acrobat Reader, will always print correctly, and display exactly as created across fonts, software and operating systems. PDF files are also compact in size and can download pages quickly for viewing on the web.
BLAST is a novel presentation format that encourages rapid knowledge transfer through short slides of 8 words or less to avoid "death by powerpoint". It aims to efficiently convey key information in a brief format. The presentation and additional references on the BLAST format can be found at blast.emcrit.org.
BLAST is a novel presentation format that encourages rapid knowledge transfer through short slides of 8 words or less to avoid "death by powerpoint". It aims to efficiently convey key information in a brief format. The presentation and additional references on the BLAST format can be found at blast.emcrit.org.
The document discusses how to compile LaTeX (.tex) files into PDF files using pdflatex. It recommends tools like pdflatex, acroread, ghostscript, and ghostview. It also provides instructions on writing LaTeX documents, including creating a main document file and chapter files, and using spellcheck. Finally, it discusses LaTeX and pdfLaTeX capabilities like fonts, math symbols, and hyperlinks.
BLAST is a novel presentation format that encourages rapid knowledge transfer through short slides of 8 words or less to avoid "death by powerpoint". It aims to efficiently convey key information in a brief format. The presentation and additional references on the BLAST format can be found at blast.emcrit.org.
This one sentence document does not provide enough context or information to create an accurate 3 sentence summary. The document contains only one word - "Lorem" - which is not meaningful on its own.
This document provides tips for creating effective PowerPoint slides by avoiding common pitfalls. It addresses how to structure slides with outlines and bullet points, use fonts and colors that are easy to read, include graphs and charts to visualize data, check for spelling and grammar errors, and conclude with a clear summary and invitation for questions. Specifically, the tips suggest using 1-2 slides per minute, including 4-5 bullet points per slide, font sizes of 18 points or larger, consistent backgrounds, labeling all graphs, and proofreading for errors.
This document provides an overview of Microsoft PowerPoint and its features for creating presentations. It demonstrates how PowerPoint can be used to produce slide shows with animation effects, different layouts including images, charts and organization charts. Templates allow standardizing the design across slides. The document walks through examples of animation, layouts, charts and templates to illustrate PowerPoint's capabilities for beginners.
This document provides an overview of Microsoft PowerPoint and its features for creating presentations. It demonstrates how PowerPoint can be used to produce slide shows with animation effects, different layouts including images, charts and organization charts. Templates allow standardizing the design across slides. The document walks through examples of animation, data graphs, organization charts and backgrounds to illustrate PowerPoint's capabilities.
The document provides a test case but does not contain any substantive information. It consists solely of the phrase "DOC 1 TEST" and lacks details, context or a clear purpose. In just 3 words, it introduces a document labeled as a test but provides no meaningful content to summarize.
HelloPT is an application that allows users to control PowerPoint presentations from an iPhone or iPod touch. It provides major functions like slide navigation and control, slide notes, and using the screen as a digital whiteboard. The application works with PowerPoint 2000 through 2010 on Windows XP, Vista or 7, and requires installation of the HelloPT Server software on a Windows server.
HelloPT is an application that allows users to control PowerPoint presentations from an iPhone or iPod touch. It provides major functions like slide navigation and control, slide notes, and using the screen as a digital whiteboard. The application works with PowerPoint 2000 through 2010 on Windows XP, Vista or 7, and requires installation of the HelloPT Server software on a Windows server.
1. Sep 7, 2015 Advanced Programming
Spring 2002
Python
Henning Schulzrinne
Department of Computer Science
Columbia University
(based on tutorial by Guido van Rossum)
2. Sep 7, 2015 Advanced
Introduction
Most recent popular
(scripting/extension) language
although origin ~1991
heritage: teaching language (ABC)
Tcl: shell
perl: string (regex) processing
object-oriented
rather than add-on (OOTcl)
3. Sep 7, 2015 Advanced
Python philosophy
Coherence
not hard to read, write and maintain
power
scope
rapid development + large systems
objects
integration
hybrid systems
4. Sep 7, 2015 Advanced
Python features
no compiling or linking rapid development cycle
no type declarations simpler, shorter, more flexible
automatic memory management garbage collection
high-level data types and
operations
fast development
object-oriented programming code structuring and reuse, C++
embedding and extending in C mixed language systems
classes, modules, exceptions "programming-in-the-large" support
dynamic loading of C modules simplified extensions, smaller
binaries
dynamic reloading of C modules programs can be modified without
stopping
Lutz, Programming Python
5. Sep 7, 2015 Advanced
Python features
universal "first-class" object model fewer restrictions and rules
run-time program construction handles unforeseen needs, end-
user coding
interactive, dynamic nature incremental development and
testing
access to interpreter information metaprogramming, introspective
objects
wide portability cross-platform programming
without ports
compilation to portable byte-code execution speed, protecting source
code
built-in interfaces to external
services
system tools, GUIs, persistence,
databases, etc.
Lutz, Programming Python
6. Sep 7, 2015 Advanced
Python
elements from C++, Modula-3
(modules), ABC, Icon (slicing)
same family as Perl, Tcl, Scheme,
REXX, BASIC dialects
7. Sep 7, 2015 Advanced
Uses of Python
shell tools
system admin tools, command line programs
extension-language work
rapid prototyping and development
language-based modules
instead of special-purpose parsers
graphical user interfaces
database access
distributed programming
Internet scripting
8. Sep 7, 2015 Advanced
What not to use Python (and
kin) for
most scripting languages share these
not as efficient as C
but sometimes better built-in algorithms
(e.g., hashing and sorting)
delayed error notification
lack of profiling tools
9. Sep 7, 2015 Advanced
Using python
/usr/local/bin/python
#! /usr/bin/env python
interactive use
Python 1.6 (#1, Sep 24 2000, 20:40:45) [GCC 2.95.1 19990816 (release)] on sunos5
Copyright (c) 1995-2000 Corporation for National Research Initiatives.
All Rights Reserved.
Copyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.
All Rights Reserved.
>>>
python –c command [arg] ...
python –i script
read script first, then interactive
10. Sep 7, 2015 Advanced
Python structure
modules: Python source files or C extensions
import, top-level via from, reload
statements
control flow
create objects
indentation matters – instead of {}
objects
everything is an object
automatically reclaimed when no longer needed
11. Sep 7, 2015 Advanced
First example
#!/usr/local/bin/python
# import systems module
import sys
marker = '::::::'
for name in sys.argv[1:]:
input = open(name, 'r')
print marker + name
print input.read()
12. Sep 7, 2015 Advanced
Basic operations
Assignment:
size = 40
a = b = c = 3
Numbers
integer, float
complex numbers: 1j+3, abs(z)
Strings
'hello world', 'it's hot'
"bye world"
continuation via or use """ long text """"
13. Sep 7, 2015 Advanced
String operations
concatenate with + or neighbors
word = 'Help' + x
word = 'Help' 'a'
subscripting of strings
'Hello'[2] 'l'
slice: 'Hello'[1:2] 'el'
word[-1] last character
len(word) 5
immutable: cannot assign to subscript
14. Sep 7, 2015 Advanced
Lists
lists can be heterogeneous
a = ['spam', 'eggs', 100, 1234, 2*2]
Lists can be indexed and sliced:
a[0] spam
a[:2] ['spam', 'eggs']
Lists can be manipulated
a[2] = a[2] + 23
a[0:2] = [1,12]
a[0:0] = []
len(a) 5
15. Sep 7, 2015 Advanced
Basic programming
a,b = 0, 1
# non-zero = true
while b < 10:
# formatted output, without n
print b,
# multiple assignment
a,b = b, a+b
16. Sep 7, 2015 Advanced
Control flow: if
x = int(raw_input("Please enter #:"))
if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
no case statement
17. Sep 7, 2015 Advanced
Control flow: for
a = ['cat', 'window', 'defenestrate']
for x in a:
print x, len(x)
no arithmetic progression, but
range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for i in range(len(a)):
print i, a[i]
do not modify the sequence being iterated
over
18. Sep 7, 2015 Advanced
Loops: break, continue, else
break and continue like C
else after loop exhaustion
for n in range(2,10):
for x in range(2,n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is prime'
19. Sep 7, 2015 Advanced
Do nothing
pass does nothing
syntactic filler
while 1:
pass
20. Sep 7, 2015 Advanced
Defining functions
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
while b < n:
print b,
a, b = b, a+b
>>> fib(2000)
First line is docstring
first look for variables in local, then global
need global to assign global variables
21. Sep 7, 2015 Advanced
Functions: default argument
values
def ask_ok(prompt, retries=4,
complaint='Yes or no, please!'):
while 1:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return 1
if ok in ('n', 'no'): return 0
retries = retries - 1
if retries < 0: raise IOError,
'refusenik error'
print complaint
>>> ask_ok('Really?')
22. Sep 7, 2015 Advanced
Keyword arguments
last arguments can be given as keywords
def parrot(voltage, state='a stiff', action='voom',
type='Norwegian blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "Volts through it."
print "Lovely plumage, the ", type
print "-- It's", state, "!"
parrot(1000)
parrot(action='VOOOM', voltage=100000)
23. Sep 7, 2015 Advanced
Lambda forms
anonymous functions
may not work in older versions
def make_incrementor(n):
return lambda x: x + n
f = make_incrementor(42)
f(0)
f(1)
24. Sep 7, 2015 Advanced
List methods
append(x)
extend(L)
append all items in list (like Tcl lappend)
insert(i,x)
remove(x)
pop([i]), pop()
create stack (FIFO), or queue (LIFO) pop(0)
index(x)
return the index for value x
25. Sep 7, 2015 Advanced
List methods
count(x)
how many times x appears in list
sort()
sort items in place
reverse()
reverse list
26. Sep 7, 2015 Advanced
Functional programming
tools
filter(function, sequence)
def f(x): return x%2 != 0 and x%3 0
filter(f, range(2,25))
map(function, sequence)
call function for each item
return list of return values
reduce(function, sequence)
return a single value
call binary function on the first two items
then on the result and next item
iterate
27. Sep 7, 2015 Advanced
List comprehensions (2.0)
Create lists without map(),
filter(), lambda
= expression followed by for clause +
zero or more for or of clauses
>>> vec = [2,4,6]
>>> [3*x for x in vec]
[6, 12, 18]
>>> [{x: x**2} for x in vec}
[{2: 4}, {4: 16}, {6: 36}]
28. Sep 7, 2015 Advanced
List comprehensions
cross products:
>>> vec1 = [2,4,6]
>>> vec2 = [4,3,-9]
>>> [x*y for x in vec1 for y in vec2]
[8,6,-18, 16,12,-36, 24,18,-54]
>>> [x+y for x in vec1 and y in vec2]
[6,5,-7,8,7,-5,10,9,-3]
>>> [vec1[i]*vec2[i] for i in
range(len(vec1))]
[8,12,-54]
29. Sep 7, 2015 Advanced
List comprehensions
can also use if:
>>> [3*x for x in vec if x > 3]
[12, 18]
>>> [3*x for x in vec if x < 2]
[]
30. Sep 7, 2015 Advanced
del – removing list items
remove by index, not value
remove slices from list (rather than by
assigning an empty list)
>>> a = [-1,1,66.6,333,333,1234.5]
>>> del a[0]
>>> a
[1,66.6,333,333,1234.5]
>>> del a[2:4]
>>> a
[1,66.6,1234.5]
31. Sep 7, 2015 Advanced
Tuples and sequences
lists, strings, tuples: examples of
sequence type
tuple = values separated by commas
>>> t = 123, 543, 'bar'
>>> t[0]
123
>>> t
(123, 543, 'bar')
32. Sep 7, 2015 Advanced
Tuples
Tuples may be nested
>>> u = t, (1,2)
>>> u
((123, 542, 'bar'), (1,2))
kind of like structs, but no element names:
(x,y) coordinates
database records
like strings, immutable can't assign to
individual items
34. Sep 7, 2015 Advanced
Tuples
sequence unpacking distribute
elements across variables
>>> t = 123, 543, 'bar'
>>> x, y, z = t
>>> x
123
packing always creates tuple
unpacking works for any sequence
35. Sep 7, 2015 Advanced
Dictionaries
like Tcl or awk associative arrays
indexed by keys
keys are any immutable type: e.g., tuples
but not lists (mutable!)
uses 'key: value' notation
>>> tel = {'hgs' : 7042, 'lennox': 7018}
>>> tel['cs'] = 7000
>>> tel
36. Sep 7, 2015 Advanced
Dictionaries
no particular order
delete elements with del
>>> del tel['foo']
keys() method unsorted list of keys
>>> tel.keys()
['cs', 'lennox', 'hgs']
use has_key() to check for existence
>>> tel.has_key('foo')
0
37. Sep 7, 2015 Advanced
Conditions
can check for sequence membership with is
and is not:
>>> if (4 in vec):
... print '4 is'
chained comparisons: a less than b AND b
equals c:
a < b == c
and and or are short-circuit operators:
evaluated from left to right
stop evaluation as soon as outcome clear
38. Sep 7, 2015 Advanced
Conditions
Can assign comparison to variable:
>>> s1,s2,s3='', 'foo', 'bar'
>>> non_null = s1 or s2 or s3
>>> non_null
foo
Unlike C, no assignment within
expression
39. Sep 7, 2015 Advanced
Comparing sequences
unlike C, can compare sequences (lists,
tuples, ...)
lexicographical comparison:
compare first; if different outcome
continue recursively
subsequences are smaller
strings use ASCII comparison
can compare objects of different type, but
by type name (list < string < tuple)
41. Sep 7, 2015 Advanced
Modules
collection of functions and variables,
typically in scripts
definitions can be imported
file name is module name + .py
e.g., create module fibo.py
def fib(n): # write Fib. series up to n
...
def fib2(n): # return Fib. series up to n
42. Sep 7, 2015 Advanced
Modules
import module:
import fibo
Use modules via "name space":
>>> fibo.fib(1000)
>>> fibo.__name__
'fibo'
can give it a local name:
>>> fib = fibo.fib
>>> fib(500)
43. Sep 7, 2015 Advanced
Modules
function definition + executable statements
executed only when module is imported
modules have private symbol tables
avoids name clash for global variables
accessible as module.globalname
can import into name space:
>>> from fibo import fib, fib2
>>> fib(500)
can import all names defined by module:
>>> from fibo import *
44. Sep 7, 2015 Advanced
Module search path
current directory
list of directories specified in PYTHONPATH
environment variable
uses installation-default if not defined, e.g.,
.:/usr/local/lib/python
uses sys.path
>>> import sys
>>> sys.path
['', 'C:PROGRA~1Python2.2', 'C:Program
FilesPython2.2DLLs', 'C:Program
FilesPython2.2lib', 'C:Program
FilesPython2.2liblib-tk', 'C:Program
FilesPython2.2', 'C:Program FilesPython2.2libsite-
packages']
45. Sep 7, 2015 Advanced
Compiled Python files
include byte-compiled version of module if
there exists fibo.pyc in same directory as
fibo.py
only if creation time of fibo.pyc matches
fibo.py
automatically write compiled file, if possible
platform independent
doesn't run any faster, but loads faster
can have only .pyc file hide source
48. Sep 7, 2015 Advanced
Classes
mixture of C++ and Modula-3
multiple base classes
derived class can override any methods of its
base class(es)
method can call the method of a base class
with the same name
objects have private data
C++ terms:
all class members are public
all member functions are virtual
no constructors or destructors (not needed)
49. Sep 7, 2015 Advanced
Classes
classes (and data types) are objects
built-in types cannot be used as base
classes by user
arithmetic operators, subscripting can
be redefined for class instances (like C+
+, unlike Java)
50. Sep 7, 2015 Advanced
Class definitions
Class ClassName:
<statement-1>
...
<statement-N>
must be executed
can be executed conditionally (see Tcl)
creates new namespace
51. Sep 7, 2015 Advanced
Namespaces
mapping from name to object:
built-in names (abs())
global names in module
local names in function invocation
attributes = any following a dot
z.real, z.imag
attributes read-only or writable
module attributes are writeable
52. Sep 7, 2015 Advanced
Namespaces
scope = textual region of Python program
where a namespace is directly accessible
(without dot)
innermost scope (first) = local names
middle scope = current module's global names
outermost scope (last) = built-in names
assignments always affect innermost scope
don't copy, just create name bindings to objects
global indicates name is in global scope
53. Sep 7, 2015 Advanced
Class objects
obj.name references (plus module!):
class MyClass:
"A simple example class"
i = 123
def f(self):
return 'hello world'
>>> MyClass.i
123
MyClass.f is method object
54. Sep 7, 2015 Advanced
Class objects
class instantiation:
>>> x = MyClass()
>>> x.f()
'hello world'
creates new instance of class
note x = MyClass vs. x = MyClass()
___init__() special method for
initialization of object
def __init__(self,realpart,imagpart):
self.r = realpart
self.i = imagpart
55. Sep 7, 2015 Advanced
Instance objects
attribute references
data attributes (C++/Java data
members)
created dynamically
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print x.counter
del x.counter
56. Sep 7, 2015 Advanced
Method objects
Called immediately:
x.f()
can be referenced:
xf = x.f
while 1:
print xf()
object is passed as first argument of
function 'self'
x.f() is equivalent to MyClass.f(x)
57. Sep 7, 2015 Advanced
Notes on classes
Data attributes override method
attributes with the same name
no real hiding not usable to
implement pure abstract data types
clients (users) of an object can add data
attributes
first argument of method usually called
self
'self' has no special meaning (cf. Java)
58. Sep 7, 2015 Advanced
Another example
bag.py
class Bag:
def __init__(self):
self.data = []
def add(self, x):
self.data.append(x)
def addtwice(self,x):
self.add(x)
self.add(x)
59. Sep 7, 2015 Advanced
Another example, cont'd.
invoke:
>>> from bag import *
>>> l = Bag()
>>> l.add('first')
>>> l.add('second')
>>> l.data
['first', 'second']
60. Sep 7, 2015 Advanced
Inheritance
class DerivedClassName(BaseClassName)
<statement-1>
...
<statement-N>
search class attribute, descending
chain of base classes
may override methods in the base class
call directly via BaseClassName.method
61. Sep 7, 2015 Advanced
Multiple inheritance
class DerivedClass(Base1,Base2,Base3):
<statement>
depth-first, left-to-right
problem: class derived from two classes
with a common base class
62. Sep 7, 2015 Advanced
Private variables
No real support, but textual replacement
(name mangling)
__var is replaced by
_classname_var
prevents only accidental modification,
not true protection
63. Sep 7, 2015 Advanced
~ C structs
Empty class definition:
class Employee:
pass
john = Employee()
john.name = 'John Doe'
john.dept = 'CS'
john.salary = 1000
65. Sep 7, 2015 Advanced
Handling exceptions
while 1:
try:
x = int(raw_input("Please enter a number: "))
break
except ValueError:
print "Not a valid number"
First, execute try clause
if no exception, skip except clause
if exception, skip rest of try clause and use except
clause
if no matching exception, attempt outer try
statement
66. Sep 7, 2015 Advanced
Handling exceptions
try.py
import sys
for arg in sys.argv[1:]:
try:
f = open(arg, 'r')
except IOError:
print 'cannot open', arg
else:
print arg, 'lines:', len(f.readlines())
f.close
e.g., as python try.py *.py