Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.

Slides:



Advertisements
Similar presentations
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Advertisements

C Language.
Python Objects and Classes
Object-Oriented Programming
Object-Oriented Programming Python. OO Paradigm - Review Three Characteristics of OO Languages –Inheritance It isn’t necessary to build every class from.
Control Structures Any mechanism that departs from straight-line execution: –Selection: if-statements –Multiway-selection: case statements –Unbounded iteration:
Coding Standard: General Rules 1.Always be consistent with existing code. 2.Adopt naming conventions consistent with selected framework. 3.Use the same.
C++ How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
Lists Introduction to Computing Science and Programming I.
VBA Modules, Functions, Variables, and Constants
Loops – While, Do, For Repetition Statements Introduction to Arrays
The Python Programming Language Matt Campbell | Steve Losh.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
CS0007: Introduction to Computer Programming Introduction to Arrays.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Scope.
Python Crash Course Classes 3 rd year Bachelors V1.0 dd Hour 7.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Lists in Python.
CSC1018F: Object Orientation, Exceptions and File Handling Diving into Python Ch. 5&6 Think Like a Comp. Scientist Ch
Python November 28, Unit 9+. Local and Global Variables There are two main types of variables in Python: local and global –The explanation of local and.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Python III CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
By: Chris Harvey Python Classes. Namespaces A mapping from names to objects Different namespaces have different mappings Namespaces have varying lifetimes.
Arrays Module 6. Objectives Nature and purpose of an array Using arrays in Java programs Methods with array parameter Methods that return an array Array.
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
Learners Support Publications Classes and Objects.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Built-in Data Structures in Python An Introduction.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
1 Tutorial 14 Validating Documents with Schemas Exploring the XML Schema Vocabulary.
Tutorial 13 Validating Documents with Schemas
Python Functions.
©Fraser Hutchinson & Cliff Green C++ Certificate Program C++ Intermediate Operator Overloading.
Introduction to OOP OOP = Object-Oriented Programming OOP is very simple in python but also powerful What is an object? data structure, and functions (methods)
CLASSES Python Workshop. Introduction  Compared with other programming languages, Python’s class mechanism adds classes with a minimum of new syntax.
P YTHON ’ S C LASSES Ian Wynyard. I NTRODUCTION TO C LASSES A class is the scope in which code is executed A class contains objects and functions that.
Overview The Basics – Python classes and objects Procedural vs OO Programming Entity modelling Operations / methods Program flow OOP Concepts and user-defined.
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
Liang, Introduction to C++ Programming, (c) 2007 Pearson Education, Inc. All rights reserved X 1 Chapter Array Basics.
Structuring Data: Arrays ANSI-C. Representing multiple homogenous data Problem: Input: Desired output:
LECTURE 6 Advanced Functions and OOP. FUNCTIONS Before we start, let’s talk about how name resolution is done in Python: When a function executes, a new.
Controlling Program Flow with Decision Structures.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
 Python for-statements can be treated the same as for-each loops in Java Syntax: for variable in listOrstring: body statements Example) x = "string"
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
CSCI/CMPE 4341 Topic: Programming in Python Chapter 7: Introduction to Object- Oriented Programming in Python – Exercises Xiang Lian The University of.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
Inheritance Modern object-oriented (OO) programming languages provide 3 capabilities: encapsulation inheritance polymorphism which can improve the design,
Test 2 Review Outline.
Data Type and Function Prepared for CSB210 Pemrograman Berorientasi Objek By Indriani Noor Hapsari, ST, MT Source: study.
Object Oriented Programming in Python: Defining Classes
Creating and Deleting Instances Access to Attributes and Methods
Python Classes By Craig Pennell.
Arrays, For loop While loop Do while loop
Python Primer 2: Functions and Control Flow
Bryan Burlingame 03 October 2018
CISC101 Reminders Assn 3 due tomorrow, 7pm.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
CSCE 590 Web Scraping: Lecture 2
CSCE 590 Web Scraping: Lecture 2
CISC101 Reminders Assignment 3 due today.
SPL – PS1 Introduction to C++.
SPL – PS2 C++ Memory Handling.
Presentation transcript:

Python: Classes By Matt Wufsus

Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the function abs(), and built-in exception names; the global names in a module; local names in a function invocation. ◦There is no relationship between names in different namespaces. ◦Namespaces are created at different moments and have different lifetimes.  The namespace containing the built-in names is created when the Python interpreter starts up, and is never deleted.  The global namespace for a module is created when the module definition is read in.  The local namespace for a function is created when the function is called, and deleted when the function returns or raises an exception that isn’t handled in the function.

Scopes and Namespaces cont. A scope is a textual region of a Python program where a namespace is directly accessible. ◦Meaning that an unqualified reference to a name attempts to find the name in the namespace. ◦Scopes are determined statically, but used dynamically.  At any time during execution, there are at least three nested scopes who namespaces are directly accessible: ◦ Innermost scope, which is searched first, containing the local names ◦ Scopes of enclosing functions, which are searched starting with the nearest enclosing scope. ◦ Next-to-last scope, containing the current module’s global names. ◦ Outermost scope, the namespace containing built-in names.

Scopes and Namespaces cont. Usually, the local scope references the local names of the (textually) current function. Outside functions, the local scope references the same namespace as the global scope: the module’s namespace. Class definitions place yet another namespace in the local scope. ◦Scopes are determined textually:  The global scope of a function defined in a module is that module’s namespace, no matter from where or by what alias that function is called. ◦ Actual search for names is done dynamically, at run time. ◦ If no global statement is in effect, assignments to names always go into the innermost scope.

Class Definition When a class is defined, a new namespace is created, and all assignments to local variables go into this new namespace. class ClassName:. Example class: class MyClass: """A simple example class""" i = def f(self): return 'hello world'

Class Objects Attribute references use standard syntax. In the example class: class MyClass: """A simple example class""" i = def f(self): return 'hello world' ◦ MyClass.i would return an integer, and MyClass.f would return an object. ◦Class attributes, like MyClass.i, can have their values changed by assignment. ◦ __doc__ is also a valid attribute that will return the docstring belonging to the class. In the example class: “A simple example class”

Class Objects cont. Class instantiation uses function notation. ◦As if the class object is a parameterless function that returns a new instance of the class For the example class: x = MyClass() ◦This creates a new instance of the class and assigns this object to the local variable x. ◦Instantiation creates an empty object, so many classes like to define special methods that create objects with instances customized to a specific initial state. For the example class: def __init__(self): self.data = []

Class Objects cont. ◦When a class defines an __init__() method, the class instantiation invokes __init__() for the newly-created class instance. ◦The __init__() method may have arguments for greater ◦flexibility. For the example class: >>> class Complex:... def __init__(self, realpart, imagpart):... self.r = realpart... self.i = imagpart... >>> x = Complex(3.0, -4.5) >>> x.r, x.i (3.0, -4.5)

Instance Objects The only operations understood by instance objects are attribute references. There are two kinds of valid attribute names, data attributes and methods. Data attributes correspond to “instance variables”. They need not be declared. In the example class, this piece of code will print the value 16 without leaving a trace: x.counter = 1 while x.counter < 10: x.counter = x.counter * 2 print x.counter del x.counter

Instance Objects cont. The other kind of instance attribute reference is a method. A method is a function that “belongs to” an object. Valid method names of an instance object depend on its class. By definition all attributes of a class that are function objects define corresponding methods of its instances. In the example class, x.f is a valid method reference, since MyClass.f is a function, but x.i is not, since MyClass.i is not. But x.f is not the same thing as MyClass.f — it is a method object, not a function object.

Method Object Usually, a method is called right after it is bound: In the example, the following will return the string hello world. x.f() However, it is not necesssary to call a method right away as they can be stored away and called at a later time. For example, this will print hello world over and over: xf = x.f while True: print xf()

Inheritance Python, like most other languages, has inheritance, as well as multiple inheritance. In the following example, the name BaseClassName must be defined in a scope containing the derived class definition. class DerivedClassName(BaseClassName):. In place of a base class name, other arbitrary expressions are allowed. class DerivedClassName (modname.BaseClassName):

Inheritance cont. A class definition with multiple base classes looks like this class DerivedClassName(Base1,Base2,Base3):. Python has two built-in functions that work with inheritance: ◦ isinstance() checks an instance’s type, and will return True only if obj. __clas__ is int or some class derived from int. ◦ issubclass() checks class inheritance  For example: issubclass(bool, int) is True since boo l is a subclass of int.

Private Variables “Private” instance variables that cannot be accessed except from inside an object don’t exist in Python. But, most Python code follows the convention in which a name prefixed with an underscore, like _spam, should be treated as a non-public part of the API. Name mangling is a limited support mechanism in which any identifier of the form __spam (two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name.

Exceptions User-defined exceptions are indentified by classes as well. It is also possible to create extensible hierarchies of exceptions. Valid raise statements: raise Class, instance raise instance

Iterators You can define an __iter__() method which returns an object with a next(). When there are no more elements, next() raises a StopIteration which tells the for loop to terminate. An example would be: class Reverse: "Iterator for looping over a sequence backwards" def __init__(self, data): self.data = data self.index = len(data) def __iter__(self): return self def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] >>> for char in Reverse('spam'):...print char... m a p s

Generators Written like regular functions, but use the yield statement whenever they want to return data. Each time next() is called, the generator resumes where it left-off. A trivial example is: def reverse(data): for index in range(len(data)-1, -1, -1): yield data[index] >>> for char in reverse('golf'):... print char... f l o g

Generator Expressions You can use generator expressions, instead of writing a full generator definition to quickly create a simple generator. Some examples: >>> sum(i*i for i in range(10)) # sum of squares 285 >>> data = 'golf‘ >>> list(data[i] for i in range(len(data)-1,-1,-1)) ['f', 'l', 'o', 'g'] # puts reveresed string into list

Questions? The Python Tutorial in the Python v2.6.4 documentation explains every Class topic in great detail with more examples than I have provided in this presentation.

References Python v2.6.4 documentation >> The Python Tutorial >> Classes ◦