python programming - viii. inheritance and polymorphism

55
VIII. INHERITANCE AND POLYMORPHISM PYTHON PROGRAMMING Engr. RANEL O. PADON

Upload: engr-ranel-padon

Post on 15-Jan-2015

612 views

Category:

Technology


5 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Python Programming - VIII. Inheritance and Polymorphism

VIII. INHERITANCE AND POLYMORPHISM

PYTHON PROGRAMMING Engr. RANEL O. PADON

Page 2: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE

Page 3: Python Programming - VIII. Inheritance and Polymorphism

PYTHON PROGRAMMING TOPICS

I•Introduction to Python Programming

II•Python Basics

III•Controlling the Program Flow

IV•Program Components: Functions, Classes, Packages, and Modules

V•Sequences (List and Tuples), and Dictionaries

VI•Object-Based Programming: Classes and Objects

VII•Customizing Classes and Operator Overloading

VIII•Object-Oriented Programming: Inheritance and Polymorphism

IX•Randomization Algorithms

X•Exception Handling and Assertions

XI•String Manipulation and Regular Expressions

XII•File Handling and Processing

XIII•GUI Programming Using Tkinter

Page 4: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Background

Object-Based Programming

programming using objects

Object-Oriented Programming

programming using objects & hierarchies

Page 5: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Background

Object-Oriented Programming

A family of classes is known as a class hierarchy.

As in a biological family, there are parent classes and child

classes.

Page 6: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Background

Object-Oriented Programming

the parent class is usually called base class or superclass

the child class is known as a derived class or subclass

Page 7: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Background

Object-Oriented Programming

Child classes can inherit data and methods from parent

classes, they can modify these data and methods, and they can

add their own data and methods.

The original class is still available and the separate child class is

small, since it does not need to repeat the code in the parent

class.

Page 8: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Background

Object-Oriented Programming

The magic of object-oriented programming is that other parts of

the code do not need to distinguish whether an object is the

parent or the child – all generations in a family tree can be

treated as a unified object.

Page 9: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Background

Object-Oriented Programming

In other words, one piece of code can work with all members

in a class family or hierarchy. This principle has revolutionized

the development of large computer systems.

Page 10: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Reusing Attributes

Page 11: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Reusing Attributes

Page 12: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE The Media Hierarchy

Page 13: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Base and Derived Classes

Page 14: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE The CommunityMember Base Class

Page 15: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE The Shape Hierarchy

Page 16: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Sample Implementation 1

Magulang

Anak

Page 17: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Magulang Base Class

class Magulang:def __init__(self, pangalan, kayamanan):

self.pangalan = pangalanself.kayamanan = kayamanan

Page 18: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Anak Derived Class

class Magulang:def __init__(self, pangalan, kayamanan):

self.pangalan = pangalanself.kayamanan = kayamanan

class Anak(Magulang):def __init__(self, pangalan = "Juan Tamad", kayamanan = 1000000):

Magulang.__init__(self, pangalan, kayamanan)

Page 19: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Sample Execution

class Magulang:def __init__(self, pangalan, kayamanan):

self.pangalan = pangalanself.kayamanan = kayamanan

class Anak(Magulang):def __init__(self, pangalan, kayamanan):

Magulang.__init__(self, pangalan, kayamanan)

gorio = Anak("Mang Gorio", 1000000)print gorio.pangalanprint gorio.kayamanan

Page 20: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Anak with Default Args

class Magulang:def __init__(self, pangalan, kayamanan):

self.pangalan = pangalanself.kayamanan = kayamanan

class Anak(Magulang):def __init__(self, pangalan = "Juan Tamad", kayamanan = 1000):

Magulang.__init__(self, pangalan, kayamanan)

print Anak().pangalanprint Anak().kayamanan

Page 21: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Magulang with instance method

class Magulang:def __init__(self, pangalan, kayamanan):

self.pangalan = pangalanself.kayamanan = kayamanan

def getKayamanan(self):return self.kayamanan

class Anak(Magulang):def __init__(self, pangalan = "Juan Tamad", kayamanan = 1000):

Magulang.__init__(self, pangalan, kayamanan)

print Anak().pangalanprint Anak().getKayamanan()

Page 22: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Sample Implementation 2

Rectangle

Square

Page 23: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Rectangle Base Class

class Rectangle():def __init__(self, lapad, haba):

self.lapad = lapadself.haba = haba

def getArea(self):return self.lapad*self.haba

Page 24: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Square Derived Class

class Rectangle():def __init__(self, lapad, haba):

self.lapad = lapadself.haba = haba

def getArea(self):return self.lapad*self.haba

class Square(Rectangle):def __init__(self, lapad):

Rectangle.__init__(self, lapad, lapad)

def getArea(self):return self.lapad**2

Page 25: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Sample Execution

class Rectangle():def __init__(self, lapad, haba):

self.lapad = lapadself.haba = haba

def getArea(self):return self.lapad*self.haba

class Square(Rectangle):def __init__(self, lapad):

Rectangle.__init__(self, lapad, lapad)

def getArea(self):return self.lapad**2

print Square(3).getArea()

Page 26: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Deadly Diamond of Death

Villains

VampireWerewolf

bite()

Vampire

bite()

Dark Side

Forces

attack()

Hybrid

What would be the version of bite() that will be used by Hybrid?

Page 27: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Deadly Diamond of Death

Villains

VampireWerewolf

bite()

Vampire

bite()

Dark Side

Forces

attack()

Hybrid

Python allow a limited form of multiple

inheritance hence care must be

observed to avoid name collisions or

ambiguity.

Other languages, like Java, do not allow

multiple inheritance.

Page 28: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Polymorphism

Polymorphism is a consequence of inheritance. It is concept

wherein a name may denote instances of many different classes as

long as they are related by some common superclass.

It is the ability of one object, to appear as and be used like another

object.

In real life, a male person could behave polymorphically:

he could be a teacher, father, husband, son, etc depending on the

context of the situation or the persons he is interacting with.

Page 29: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Polymorphism

Polymorphism is also applicable to systems with same base/core

components or systems interacting via unified interfaces.

USB plug and play devices

“.exe” files

Linux kernel as used in various distributions

(Ubuntu, Fedora, Mint, Arch)

Linux filesystems (in Linux everything is a file)

The beauty of it is that you could make small code changes

but it could be utilized by all objects inheriting or

interacting with it.

Page 30: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Polymorphism

Page 31: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Polymorphism

Hugis

BilogTatsulok

Page 32: Python Programming - VIII. Inheritance and Polymorphism

class Hugis():def __init__(self, pangalan):

self.pangalan = pangalan

INHERITANCE Polymorphism

Page 33: Python Programming - VIII. Inheritance and Polymorphism

class Hugis():def __init__(self, pangalan):

self.pangalan = pangalan

class Tatsulok(Hugis):def __init__(self, pangalan, pundasyon, taas):

Hugis.__init__(self, pangalan)self.pundasyon = pundasyonself.taas = taas

def getArea(self):return 0.5*self.pundasyon*self.taas

print Tatsulok("Tatsulok sa Talipapa", 3, 4).getArea()

INHERITANCE Polymorphism

Page 34: Python Programming - VIII. Inheritance and Polymorphism

class Hugis():def __init__(self, pangalan):

self.pangalan = pangalan

class Bilog(Hugis):def __init__(self, pangalan, radyus):

Hugis.__init__(self, pangalan)self.radyus = radyus

def getArea(self):return 3.1416*self.radyus**2

print Bilog("Bilugang Mundo", 2).getArea()

INHERITANCE Polymorphism

Page 35: Python Programming - VIII. Inheritance and Polymorphism

class Hugis():def __init__(self, pangalan):

class Tatsulok(Hugis):def __init__(self, pangalan, pundasyon, taas):

def getArea(self):

class Bilog(Hugis):def __init__(self, pangalan, radyus):

def getArea(self):

koleksyonNgHugis = []koleksyonNgHugis += [Tatsulok("Tatsulok sa Talipapa", 3, 4)]koleksyonNgHugis += [Bilog("Bilugang Mundo", 2)]

for i in range(len(koleksyonNgHugis)):print koleksyonNgHugis[i].getArea()

INHERITANCE Polymorphism

POLYMORPHISM

Page 36: Python Programming - VIII. Inheritance and Polymorphism

Polymorphism is not the same as method overloading or

method overriding.

Polymorphism is only concerned with the application of

specific implementations to an interface or a more generic

base class.

Method overloading refers to methods that have the same

name but different signatures inside the same class.

Method overriding is where a subclass replaces the

implementation of one or more of its parent's methods.

Neither method overloading nor method overriding are by

themselves implementations of polymorphism.

INHERITANCE Polymorphism

http://www.princeton.edu/~achaney/tmve/wiki100k/docs/Polymorphism_in_object-oriented_programming.html

Page 37: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

Page 38: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

there are cases in which we define classes but we don’t

want to create any objects

they are merely used as a base or model class

abstract base classes are too generic to define real objects,

that is, they are abstract or no physical manifestation (it’s

like the idea of knowing how a dog looks like but not

knowing how an ‘animal’ looks like, and in this case,

‘animal’ is an abstract concept)

Page 39: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

Abstract class is a powerful idea since you only have to

communicate with the parent (abstract class), and all

classes implementing that parent class will follow

accordingly. It’s also related to the Polymorphism.

Page 40: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

‘Shape’ is an abstract class. We don’t know how a ‘shape’

looks like, but we know that at a minimum it must have a

dimension or descriptor (name, length, width, height, radius,

color, rotation, etc). And these descriptors could be reused

or extended by its children.

Page 41: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

Abstract classes lay down the foundation/framework on

which their children could further extend.

Page 42: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

Page 43: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE The Gaming Metaphor

Manananggal

Gameplay Menu Options

KamponNgKadilimanTagapagligtas

MangJosePandayHalimawSaBanga

MapsMgaTauhan

Page 44: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

Abstract Classes

KamponNgKadiliman Tagapagligtas

MangJosePandayManananggal HalimawSaBanga

MgaTauhan

Page 45: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

class MgaTauhan():def __init__(self, pangalan, buhay):

if self.__class__ == MgaTauhan:raise NotImplementedError, "abstract class po ito!"

self.pangalan = pangalanself.buhay = buhay

def draw(self):raise NotImplementedError, "kelangang i-draw ito"

Page 46: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

class KamponNgKadiliman(MgaTauhan):bilang = 0def __init__(self, pangalan):

MgaTauhan.__init__(self, pangalan, 50)if self.__class__ == KamponNgKadiliman:

raise NotImplementedError, "abstract class lang po ito!"KamponNgKadiliman.bilang += 1

def attack(self):return 5

def __del__(self):KamponNgKadiliman.bilang -= 1self.isOutNumbered()

def isOutNumbered(self):if KamponNgKadiliman.bilang == 1:

print “umatras ang mga HungHang"

Page 47: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

class Tagapagligtas(MgaTauhan):bilang = 0def __init__(self, pangalan):

MgaTauhan.__init__(self, pangalan, 100)if self.__class__ == Tagapagligtas:

raise NotImplementedError, "abstract class lang po ito!"Tagapagligtas.bilang += 1

def attack(self):return 10

def __del__(self):Tagapagligtas.bilang -= 1self.isOutNumbered()

def isOutNumbered(self):if Tagapagligtas.bilang == 1:

“umatras ang ating Tagapagligtas"

Page 48: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

class Manananggal(KamponNgKadiliman):def __init__(self, pangalan):

KamponNgKadiliman.__init__(self, pangalan)

def draw(self):return "loading Mananaggal.jpg.."

def kapangyarihan(self):return "mystical na dila"

Page 49: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

class HalimawSaBanga(KamponNgKadiliman):def __init__(self, pangalan):

KamponNgKadiliman.__init__(self, pangalan)

def draw(self):return "loading HalimawSaBanga.jpg.."

def kapangyarihan(self):return "kagat at heavy-armored na banga"

Page 50: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

class Panday(Tagapagligtas):def __init__(self, pangalan):

Tagapagligtas.__init__(self, pangalan)

def draw(self):return "loading Panday.jpg.."

def kapangyarihan(self):return "titanium na espada, galvanized pa!"

Page 51: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

class MangJose(Tagapagligtas):def __init__(self, pangalan):

Tagapagligtas.__init__(self, pangalan)

def draw(self):return "loading MangJose.jpg.."

def kapangyarihan(self):return "CD-R King gadgets"

Page 52: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Abstract Class

creatures = []creatures += [Manananggal("Taga-Caloocan")]creatures += [HalimawSaBanga("Taga-Siquijor")]creatures += [MangJose("Taga-KrusNaLigas")]creatures += [MangJose("Taga-Cotabato")]creatures += [Panday("Taga-Cubao Ilalim")]

for i in range(len(creatures)):print creatures[i].draw()

print KamponNgKadiliman.bilangprint Tagapagligtas.bilangdel creatures[0]

loading Manananggal.jpg..

loading HalimawSaBanga.jpg..

loading MangJose.jpg..

loading MangJose.jpg..

loading Panday.jpg..

2

3

atras ang mga Hunghang!

This simple line is so powerful,

since it makes the current Creature

draw itself regardless of what

Creature it is!

Page 53: Python Programming - VIII. Inheritance and Polymorphism

INHERITANCE Flexibility and Power

Re-use, Improve, Extend

Page 54: Python Programming - VIII. Inheritance and Polymorphism

OOP: INHERITANCE is Powerful!

Page 55: Python Programming - VIII. Inheritance and Polymorphism

REFERENCES

Deitel, Deitel, Liperi, and Wiedermann - Python: How to Program (2001).

Disclaimer: Most of the images/information used here have no proper source citation, and I do

not claim ownership of these either. I don’t want to reinvent the wheel, and I just want to reuse

and reintegrate materials that I think are useful or cool, then present them in another light,

form, or perspective. Moreover, the images/information here are mainly used for

illustration/educational purposes only, in the spirit of openness of data, spreading light, and

empowering people with knowledge.