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. 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
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. 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. 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. 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. 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. 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. 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. 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)
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
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. 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. 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. 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()
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
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
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. 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.
30. Checking Inheritance
>>> a = A()
>>> isinstance(a, A)
True
>>> b = B()
>>> isinstance(b, B)
True
>>> isinstance(b, A)
True
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
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. 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. 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. 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
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'