Top Banner
Python & Perl Lecture 8 Department of Computer Science Utah State University
44
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Python lecture 8

Python & Perl

Lecture 8

Department of Computer ScienceUtah State University

Page 2: Python lecture 8

Outline● OOP Continued● Polymorphism ● Encapsulation● Inheritance● Introduction to Pygame

Page 3: Python lecture 8

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

Page 4: Python lecture 8

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

Page 5: Python lecture 8

Polymorphism

Page 6: Python lecture 8

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

Page 7: Python lecture 8

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) ## count is polymorphic, applied to a list

1

>>> tup.count(1) ## count is polymorphic, applied to a tuple

1

>>> str.count('1') ## count is polymorphic, applied to a string

1

Page 8: Python lecture 8

Example 2>>> lst = [1, 2, 3] ## lst is a list

>>> tup = (1, 2, 3) ## tup is a tuple

>>> str = '123' ## str is a string

>>> len(lst) ## len is polymorphic

3

>>> len(tup) ## len is polymorphic

3

>>> len(str) ## len is polymorphic

3

Page 9: Python lecture 8

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

Page 10: Python lecture 8

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

Page 11: Python lecture 8

Example from en.wikipedia.org/wiki/Duck_typingclass 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

Page 12: Python lecture 8

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()

Page 13: Python lecture 8

Example from en.wikipedia.org/wiki/Duck_typing

## game is played correctly

def game_01():

print 'Game 01'

x1 = Duck()

x2 = Person()

x2.name = 'John'

in_the_forest(x1)

in_the_forest(x2)

## run-time error occurs

def game_02():

print 'Game 02'

x1 = Duck()

x2 = [1, 2, 3]

in_the_forest(x1)

in_the_forest(x2)

Page 14: Python lecture 8

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

Page 15: Python lecture 8

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'

Page 16: Python lecture 8

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

Page 17: Python lecture 8

Encapsulation

Page 18: Python lecture 8

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.

Page 19: Python lecture 8

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

Page 20: Python lecture 8

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

Page 21: Python lecture 8

Encapsulation & Privacyclass 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()

Page 22: Python lecture 8

Encapsulation & Privacy

>>> c = C()

>>> c.f()

semi private

>>> c.x

0

>>> c.__y ## error

>>> c.__g() ## error

Page 23: Python lecture 8

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

Page 24: Python lecture 8

Inheritance

Page 25: Python lecture 8

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

Page 26: Python lecture 8

Inheritance

Page 27: Python lecture 8

Exampleclass 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.'

Page 28: Python lecture 8

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.

Page 29: Python lecture 8

Checking Inheritance

>>> B.__bases__

(<class '__main__.A'>,)

>>> issubclass(A, B)

False

>>> issubclass(B, A)

True

Page 30: Python lecture 8

Checking Inheritance>>> a = A()

>>> isinstance(a, A)

True

>>> b = B()

>>> isinstance(b, B)

True

>>> isinstance(b, A)

True

Page 31: Python lecture 8

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

Page 32: Python lecture 8

Example

Calculator Talker

calculate talk

TalkingCalculator

talkcalculate

Page 33: Python lecture 8

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

Page 34: Python lecture 8

Multiple Inheritance

>>> tc = TalkingCalculator()

## calculate is inherited from Calculator

>>> tc.calculate('1 + 2')

## talk is inherited from Talker

>>> tc.talk()

My value is 3

Page 35: Python lecture 8

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

Page 36: Python lecture 8

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

Page 37: Python lecture 8

Introduction to Pygame

Page 38: Python lecture 8

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'

Page 39: Python lecture 8

Demo

Page 40: Python lecture 8

Game Initialization

Page 41: Python lecture 8

Image Loading

Page 42: Python lecture 8

Game Loop

Page 43: Python lecture 8

Game Loop

Page 44: Python lecture 8

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 Profes-

sional, 2nd Ed., APRESS