0
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 metho...
Multiple constructors
●

●

Unlike Java, you cannot define multiple constructors.
However, you can define a default value ...
Polymorphism
Polymorphism
●

●

●

Polymorphism is a noun derived from two Greek
words poly (many) and morph (form)
Wiktionary
(http://...
Example 1
>>> lst = [1, 2, 3]

## lst is a list

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

## tup is a tuple

>>> str = '123'

## str is a stri...
Example 2
>>> lst = [1, 2, 3]

## lst is a list

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

## st...
Riley's Duck Test
●

●

In Python, polymorphism is synonymous with
duck typing
Duck typing allegedly takes its name from t...
Riley's Duck Test
●

The basic principle of duck typing can be expressed as
follows: it is not the type of the object that...
Example from en.wikipedia.org/wiki/Duck_typing
class Duck:
def quack(self):
print 'Quack!'
def feathers(self):
print 'The ...
Example from en.wikipedia.org/wiki/Duck_typing
## in_the_forest is a duck-typing function
def in_the_forest(x):
## whateve...
Example from en.wikipedia.org/wiki/Duck_typing
## game is played correctly
def game_01():
print 'Game 01'

## run-time err...
Example from en.wikipedia.org/wiki/Duck_typing
>>> game_01()
Game 01
Quack!
The duck has white and gray feathers.
The pers...
Example from en.wikipedia.org/wiki/Duck_typing
>>> game_02()
Game 02
Quack!
The duck has white and gray feathers.
Attribut...
Critique of Duck Typing
●

●

●

Duck typing increases the cognitive load on the
programmer because the programmer cannot ...
Encapsulation
Encapsulation
●

●

●

●

Encapsulation is the principle of hiding
unnecessary information (complexities) from the
world
A...
Polymorphism vs. Encapsulation
●

●

●

Both polymorphism and encapsulation are data
abstraction principles
Polymorphism a...
Encapsulation & Privacy
●

●

●

Python classes do not support privacy in the C+
+ or Java sense of that term
There is not...
Encapsulation & Privacy
class C:
x=0
__y = 1

## y has two underscores in front of it

def __g(self): ## g has two undersc...
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 prefi...
Inheritance
Inheritance
●

●

●

Inheritance is an OOP principle that supports
code reuse and abstraction
If a class C defines a set o...
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)...
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
Ca...
Example
Calculator

Talker
talk

calculate

TalkingCalculator
calculate

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

●

Download PyGame for your os at www.pygame.org
On Ubuntu and other Linux flavors, you can use the
syn...
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...
Upcoming SlideShare
Loading in...5
×

Python lecture 8

57

Published on

Published in: Education
0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total Views
57
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
3
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Transcript of "Python lecture 8"

  1. 1. Python & Perl Lecture 8 Department of Computer Science Utah State University
  2. 2. Outline ● OOP Continued ● Polymorphism ● Encapsulation ● Inheritance ● Introduction to Pygame
  3. 3. 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
  4. 4. 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
  5. 5. Polymorphism
  6. 6. 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
  7. 7. 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
  8. 8. 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
  9. 9. 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.”
  10. 10. 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
  11. 11. 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
  12. 12. 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()
  13. 13. 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)
  14. 14. 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
  15. 15. 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'
  16. 16. 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
  17. 17. Encapsulation
  18. 18. 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.
  19. 19. 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
  20. 20. 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
  21. 21. 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()
  22. 22. Encapsulation & Privacy >>> c = C() >>> c.f() semi private >>> c.x 0 >>> c.__y ## error >>> c.__g() ## error
  23. 23. 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
  24. 24. Inheritance
  25. 25. 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
  26. 26. Inheritance
  27. 27. 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.'
  28. 28. 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.
  29. 29. Checking Inheritance >>> B.__bases__ (<class '__main__.A'>,) >>> issubclass(A, B) False >>> issubclass(B, A) True
  30. 30. Checking Inheritance >>> a = A() >>> isinstance(a, A) True >>> b = B() >>> isinstance(b, B) True >>> isinstance(b, A) True
  31. 31. 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
  32. 32. Example Calculator Talker talk calculate TalkingCalculator calculate talk
  33. 33. 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
  34. 34. Multiple Inheritance >>> tc = TalkingCalculator() ## calculate is inherited from Calculator >>> tc.calculate('1 + 2') ## talk is inherited from Talker >>> tc.talk() My value is 3
  35. 35. 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
  36. 36. 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
  37. 37. Introduction to Pygame
  38. 38. 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'
  39. 39. Demo
  40. 40. Game Initialization
  41. 41. Image Loading
  42. 42. Game Loop
  43. 43. Game Loop
  44. 44. 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
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×