Python & Perl
Lecture 8

Department of Computer Science
Utah State University
Outline
●

OOP Continued

●

Polymorphism

●

Encapsulation

●

Inheritance

●

Introduction to Pygame
Constructors
●

●

●

The method __init__() is a special method, which is
called class constructor or initialization method
Called by Python interpreter when you create a new
instance of a class
This is the first method to be invoked
Multiple constructors
●

●

Unlike Java, you cannot define multiple constructors.
However, you can define a default value if one is not
passed.
def __init__(self, city="Logan"):
self.city = city
Polymorphism
Polymorphism
●

●

●

Polymorphism is a noun derived from two Greek
words poly (many) and morph (form)
Wiktionary
(http://en.wiktionary.org)
defines
polymorphism as the ability to assume multiple
forms or shapes
In OOP, polymorphism refers to the use of the
same operation on objects of different classes
Example 1
>>> lst = [1, 2, 3]

## lst is a list

>>> tup = (1, 2, 3)

## tup is a tuple

>>> str = '123'

## str is a string

>>> lst.count(1)
list

## count is polymorphic, applied to a

1
>>> tup.count(1) ## count is polymorphic, applied to a tuple
1
>>> str.count('1') ## count is polymorphic, applied to a string
1
Example 2
>>> lst = [1, 2, 3]

## lst is a list

>>> tup = (1, 2, 3) ## tup is a tuple
>>> str = '123'
>>> len(lst)

## str is a string
## len is polymorphic

3
>>> len(tup)

## len is polymorphic

3
>>> len(str)
3

## len is polymorphic
Riley's Duck Test
●

●

In Python, polymorphism is synonymous with
duck typing
Duck typing allegedly takes its name from the duck
test attributed to James Whitcomb Riley, an
American writer and poet:
“When I see a bird that walks like a duck
and swims like a duck and quacks like a
duck, I call that bird a duck.”
Riley's Duck Test
●

The basic principle of duck typing can be expressed as
follows: it is not the type of the object that
matters but the operations that the object
supports
Example from en.wikipedia.org/wiki/Duck_typing
class Duck:
def quack(self):
print 'Quack!'
def feathers(self):
print 'The duck has white and gray feathers.'
class Person:
def quack(self):
print 'The person imitates a duck.'
def feathers(self):
print 'The person takes a feather from the ground and
shows it'
def name(self):
print self.name
Example from en.wikipedia.org/wiki/Duck_typing
## in_the_forest is a duck-typing function
def in_the_forest(x):
## whatever the type of x is, just call quack
## and feathers on it
x.quack()
x.feathers()
Example from en.wikipedia.org/wiki/Duck_typing
## game is played correctly
def game_01():
print 'Game 01'

## run-time error
occurs
def game_02():

x1 = Duck()

print 'Game 02'

x2 = Person()

x1 = Duck()

x2.name = 'John'

x2 = [1, 2, 3]

in_the_forest(x1)

in_the_forest(x1)

in_the_forest(x2)

in_the_forest(x2)
Example from en.wikipedia.org/wiki/Duck_typing
>>> game_01()
Game 01
Quack!
The duck has white and gray feathers.
The person imitates a duck.
The person takes a feather from the ground and shows
it
Example from en.wikipedia.org/wiki/Duck_typing
>>> game_02()
Game 02
Quack!
The duck has white and gray feathers.
AttributeError: 'list' object has no attribute 'quack'
Critique of Duck Typing
●

●

●

Duck typing increases the cognitive load on the
programmer because the programmer cannot infer
types from local code segments and therefore
must always be aware of the big picture
Duck typing makes project planning more difficult
because in many cases only project managers
need to know the big picture
Duck typing improves software testing
Encapsulation
Encapsulation
●

●

●

●

Encapsulation is the principle of hiding
unnecessary information (complexities) from the
world
A class defines the data that its objects need
Users of objects may not want to know most of the
data
Example: Think of the complexities you ignore
while driving a car.
Polymorphism vs. Encapsulation
●

●

●

Both polymorphism and encapsulation are data
abstraction principles
Polymorphism allows the programmer to call the
methods of an object without knowing the object's
type
Encapsulation allows the programmer to
manipulate the objects of a class without knowing
how the objects are constructed
Encapsulation & Privacy
●

●

●

Python classes do not support privacy in the C+
+ or Java sense of that term
There is nothing in a Python class that can be
completely hidden from the outside world
To make a method or an attribute partially
hidden, start its name with two underscores
Encapsulation & Privacy
class C:
x=0
__y = 1

## y has two underscores in front of it

def __g(self): ## g has two underscores in front of it
print 'semi private'
def f(self):
self.__g()
Encapsulation & Privacy
>>> c = C()
>>> c.f()
semi private
>>> c.x
0
>>> c.__y

## error

>>> c.__g() ## error
Encapsulation & Privacy
●

Python converts all names that begin with double
underscores into the same names that are prefixed with
a single underscore and the class name. So they are still
accessible!
>>> c = C()
>>> C._C__y

## accessing __y

1
>>> C._C__g(c) ## accessing __g
semi private
Inheritance
Inheritance
●

●

●

Inheritance is an OOP principle that supports
code reuse and abstraction
If a class C defines a set of attributes (data and
methods), the programmer can derive a
subclass of C without having to reimplement
C's attributes
In OOP, subclasses are said to inherit
attributes of superclasses
Inheritance
Example
class A:
def f(self):
print 'A's f.'
def g(self):
print 'A's g.'
## B inherits f from A and overrides g
class B(A):
def g(self):
print 'B's g.'
Example
>>> a = A()
>>> b = B()
>>> a.f()
A's f.
>>> a.g()
A's g.
>>> b.f()
A's f.
>>> b.g()
B's g.
Checking Inheritance
>>> B.__bases__
(<class '__main__.A'>,)
>>> issubclass(A, B)
False
>>> issubclass(B, A)
True
Checking Inheritance
>>> a = A()
>>> isinstance(a, A)
True
>>> b = B()
>>> isinstance(b, B)
True
>>> isinstance(b, A)
True
Multiple Superclasses
●

●

●

●

A class in Python can have multiple superclasses:
this is called multiple inheritance
Caveat: if several superclasses implement the same
method, the method resolution order is required
The method resolution order is a graph search
algorithm
General advice: unless you really need multiple
inheritance, you should avoid it
Example
Calculator

Talker
talk

calculate

TalkingCalculator
calculate

talk
Inheritance
__metaclass__ = type
class Calculator:
def calculate(self, expression):
self.value = eval(expression)
class Talker:
def talk(self):
print 'My value is', self.value
class TalkingCalculator(Calculator, Talker):
pass
Multiple Inheritance
>>> tc = TalkingCalculator()
## calculate is inherited from Calculator
>>> tc.calculate('1 + 2')
## talk is inherited from Talker
>>> tc.talk()
My value is 3
Multiple Inheritance Pitfalls
__metaclass__ = type
class A:
def f(self): print "A's f"
class B:
def f(self): print "B's f"
## AB inherits first from A and then from B
class AB(A, B): pass
## BA inherits first from B and then from A
class BA(B, A): pass
Multiple Inheritance Pitfalls
## ab first inherits from A then from B
>>> ab = AB()
## ba first inherits from B then from A
>>> ba = BA()
## f is inherited from A
>>> ab.f()
A's f
## f is inherited from B
>>> ba.f()
B's f
Introduction to Pygame
Installations
●
●

●

Download PyGame for your os at www.pygame.org
On Ubuntu and other Linux flavors, you can use the
synaptic package manager
Here is how you can check if evrything is installed and
the installed version
>>> import pygame
>>> pygame.ver
'1.9.2pre'
Demo
Game Initialization
Image Loading
Game Loop
Game Loop
Reading & References
●

www.python.org

●

http://en.wikipedia.org/wiki/Duck_typing

●

http://en.wikipedia.org/wiki/James_Whitcomb_Riley

●

http://www.pygame.org/docs/ref/display.html

●

M. L. Hetland. Beginning Python From Novice to Professional, 2nd Ed., APRESS

Python lecture 8