Python: Classes

Download Report

Transcript Python: Classes

Python: Classes
By Matt Wufsus

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

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.
Scopes and Namespaces cont.

When a class is defined, a new namespace is
created, and all assignments to local variables go
into this new namespace.
class ClassName:
<statement-1>
.
.
.
<statement-N>
Example class:
class MyClass:
"""A simple example class"""
i = 12345
def f(self):
return 'hello world'
Class Definition

Attribute references use standard syntax.
In the example class:
class MyClass:
"""A simple example class"""
i = 12345
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

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)
Class Objects cont.

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

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.
Instance Objects cont.

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()

Method Object

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):
<statement-1>
.
.
.
<statement-N>

In place of a base class name, other arbitrary expressions are
allowed.
class DerivedClassName (modname.BaseClassName):
Inheritance

A class definition with multiple base classes looks like this
class DerivedClassName(Base1,Base2,Base3):
<statement-1>
.
.
.
<statement-N>

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 bool is a subclass of
int.
Inheritance cont.

“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.
Private Variables
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
Exceptions

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
Iterators

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
Generators
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))
285
# sum of squares
>>> data = 'golf‘
>>> list(data[i] for i in range(len(data)-1,-1,-1))
['f', 'l', 'o', 'g']
# puts reveresed string into list
Generator Expressions

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.
Questions?

Python v2.6.4 documentation >> The
Python Tutorial >> Classes
◦ http://docs.python.org/tutorial/classes.html
References