[go: up one dir, main page]

0% found this document useful (0 votes)
51 views33 pages

4 Classes Objects

Python uses namespaces to map names to objects. Namespaces are created at different times with different lifetimes, such as the built-in namespace created at interpreter startup or a module's global namespace created when the module is read in. Scopes determine which namespaces are directly accessible in a given region of code. Classes create new namespaces and scoping rules determine how names are resolved. Objects are instantiated from classes and can have data attributes and methods. Inheritance allows deriving new classes from existing classes while generators and generator expressions provide iteration abilities.

Uploaded by

Birhane Haftu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views33 pages

4 Classes Objects

Python uses namespaces to map names to objects. Namespaces are created at different times with different lifetimes, such as the built-in namespace created at interpreter startup or a module's global namespace created when the module is read in. Scopes determine which namespaces are directly accessible in a given region of code. Classes create new namespaces and scoping rules determine how names are resolved. Objects are instantiated from classes and can have data attributes and methods. Inheritance allows deriving new classes from existing classes while generators and generator expressions provide iteration abilities.

Uploaded by

Birhane Haftu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 33

Python: Classes

 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


2
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.
3
 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.
4
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
5
 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
6
 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.


7
◦ 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.


8
  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
9
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.


10
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
11
 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
12
 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.
13
“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
14
• 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
15
 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
16
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
17
• 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

Generator Expressions
18
OOP, Defining a Class
• Python was built as a procedural language
– OOP exists and works fine, but feels a bit more "tacked on"
– Java probably does classes better than Python (gasp)

• Declaring a class:
class name:
statements

19
Fields
name = value

– Example: point.py
class Point: 1 class Point:
x = 0 2 x = 0
y = 0 3 y = 0

# main
p1 = Point()
p1.x = 2
p1.y = -5

– can be declared directly inside class (as shown here)


or in constructors (more common)
– Python does not really have encapsulation or private fields
• relies on caller to "be nice" and not mess with objects' contents

20
Using a Class
import class
– client programs must import the classes they use

point_main.py
1 from Point import *
2
3 # main
4 p1 = Point()
5 p1.x = 7
6 p1.y = -3
7 ...
8
9 # Python objects are dynamic (can add fields any time!)
10 p1.name = "Tyler Durden"

21
Object Methods
def name(self, parameter, ..., parameter):
statements

– self must be the first parameter to any object method


• represents the "implicit parameter" (this in Java)

– must access the object's fields through the self reference


class Point:
def translate(self, dx, dy):
self.x += dx
self.y += dy
...

22
"Implicit" Parameter (self)
• Java: this, implicit
public void translate(int dx, int dy) {
x += dx; // this.x += dx;
y += dy; // this.y += dy;
}

• Python: self, explicit


def translate(self, dx, dy):
self.x += dx
self.y += dy

– Exercise: Write distance, set_location, and


distance_from_origin methods.

23
Exercise Answer
point.py
1 from math import *
2
3 class Point:
4 x = 0
5 y = 0
6
7 def set_location(self, x, y):
8 self.x = x
9 self.y = y
10
11 def distance_from_origin(self):
12 return sqrt(self.x * self.x + self.y * self.y)
13
14 def distance(self, other):
15 dx = self.x - other.x
16 dy = self.y - other.y
17 return sqrt(dx * dx + dy * dy)

24
Calling Methods
• A client can call the methods of an object in two ways:
– (the value of self can be an implicit or explicit parameter)

1) object.method(parameters)
or
2) Class.method(object, parameters)

• Example:
p = Point(3, -4)
p.translate(1, 5)
Point.translate(p, 1, 5)

25
Constructors
def __init__(self, parameter, ..., parameter):
statements

– a constructor is a special method with the name __init__

– Example:
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
...

• How would we make it possible to construct a


Point() with no parameters to get (0, 0)?

26
toString and __str__
def __str__(self):
return string
– equivalent to Java's toString (converts object to a string)
– invoked automatically when str or print is called

Exercise: Write a __str__ method for Point objects that


returns strings like "(3, -14)"
def __str__(self):
return "(" + str(self.x) + ", " + str(self.y) + ")"

27
Complete Point Class
point.py
1 from math import *
2
3 class Point:
4 def __init__(self, x, y):
5 self.x = x
6 self.y = y
7
8 def distance_from_origin(self):
9 return sqrt(self.x * self.x + self.y * self.y)
10
11 def distance(self, other):
12 dx = self.x - other.x
13 dy = self.y - other.y
14 return sqrt(dx * dx + dy * dy)
15
16 def translate(self, dx, dy):
17 self.x += dx
18 self.y += dy
19
20 def __str__(self):
21 return "(" + str(self.x) + ", " + str(self.y) + ")"

28
Operator Overloading
• operator overloading: You can define functions so that
Python's built-in operators can be used with your class.
• See also: http://docs.python.org/ref/customization.html

Operator Class Method Operator Class Method


- __neg__(self, other) == __eq__(self, other)
+ __pos__(self, other) != __ne__(self, other)
* __mul__(self, other) < __lt__(self, other)
/ __truediv__(self, other) > __gt__(self, other)
Unary Operators <= __le__(self, other)
- __neg__(self) >= __ge__(self, other)
+ __pos__(self)

29
Exercise
• Exercise: Write a Fraction class to represent rational
numbers like 1/2 and -3/8.

• Fractions should always be stored in reduced form; for


example, store 4/12 as 1/3 and 6/-9 as -2/3.
– Hint: A GCD (greatest common divisor) function may help.

• Define add and multiply methods that accept another


Fraction as a parameter and modify the existing
Fraction by adding/multiplying it by that parameter.

• Define +, *, ==, and < operators.

30
Generating Exceptions
raise ExceptionType("message")

– useful when the client uses your object improperly


– types: ArithmeticError, AssertionError, IndexError,
NameError, SyntaxError, TypeError, ValueError

– Example:
class BankAccount:
...
def deposit(self, amount):
if amount < 0:
raise ValueError("negative amount")
...

31
Inheritance
class name(superclass):
statements

– Example:
class Point3D(Point): # Point3D extends Point
z = 0
...

• Python also supports multiple inheritance


class name(superclass, ..., superclass):
statements
(if > 1 superclass has the same field/method, conflicts are resolved in left-to-right order)

32
Calling Superclass Methods
• methods: class.method(object,
parameters)
• constructors: class.__init__(parameters)

class Point3D(Point):
z = 0
def __init__(self, x, y, z):
Point.__init__(self, x, y)
self.z = z

def translate(self, dx, dy, dz):


Point.translate(self, dx, dy)
self.z += dz

33

You might also like