SlideShare uma empresa Scribd logo
1 de 44
Baixar para ler offline
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

Mais conteúdo relacionado

Mais procurados

Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
Jim Yeh
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
Kumar
 

Mais procurados (20)

Dive into Python Class
Dive into Python ClassDive into Python Class
Dive into Python Class
 
Structured Languages
Structured LanguagesStructured Languages
Structured Languages
 
Python Programming
Python ProgrammingPython Programming
Python Programming
 
Synapseindia dot net development
Synapseindia dot net developmentSynapseindia dot net development
Synapseindia dot net development
 
About Python
About PythonAbout Python
About Python
 
C++ oop
C++ oopC++ oop
C++ oop
 
Php object orientation and classes
Php object orientation and classesPhp object orientation and classes
Php object orientation and classes
 
Introduction to-csharp
Introduction to-csharpIntroduction to-csharp
Introduction to-csharp
 
Object oriented programming in php 5
Object oriented programming in php 5Object oriented programming in php 5
Object oriented programming in php 5
 
JAVA OOP
JAVA OOPJAVA OOP
JAVA OOP
 
Introduction toc sharp
Introduction toc sharpIntroduction toc sharp
Introduction toc sharp
 
Design of OO language
Design of OO languageDesign of OO language
Design of OO language
 
Python – Object Oriented Programming
Python – Object Oriented Programming Python – Object Oriented Programming
Python – Object Oriented Programming
 
Oops lecture 1
Oops lecture 1Oops lecture 1
Oops lecture 1
 
Class 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented ProgrammingClass 7 - PHP Object Oriented Programming
Class 7 - PHP Object Oriented Programming
 
DITEC - Programming with C#.NET
DITEC - Programming with C#.NETDITEC - Programming with C#.NET
DITEC - Programming with C#.NET
 
DISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in JavaDISE - Windows Based Application Development in Java
DISE - Windows Based Application Development in Java
 
PHP Classes and OOPS Concept
PHP Classes and OOPS ConceptPHP Classes and OOPS Concept
PHP Classes and OOPS Concept
 
7 rules of simple and maintainable code
7 rules of simple and maintainable code7 rules of simple and maintainable code
7 rules of simple and maintainable code
 
Object Oriented Programming in PHP
Object Oriented Programming  in PHPObject Oriented Programming  in PHP
Object Oriented Programming in PHP
 

Semelhante a Python lecture 8

Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
Tendayi Mawushe
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
DeepasCSE
 

Semelhante a Python lecture 8 (20)

Python_Unit_2 OOPS.pptx
Python_Unit_2  OOPS.pptxPython_Unit_2  OOPS.pptx
Python_Unit_2 OOPS.pptx
 
Object Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in PythonObject Orientation vs Functional Programming in Python
Object Orientation vs Functional Programming in Python
 
C++ theory
C++ theoryC++ theory
C++ theory
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
Python inheritance
Python inheritancePython inheritance
Python inheritance
 
Class, object and inheritance in python
Class, object and inheritance in pythonClass, object and inheritance in python
Class, object and inheritance in python
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
UNIT III (8).pptx
UNIT III (8).pptxUNIT III (8).pptx
UNIT III (8).pptx
 
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering CollegeObject Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
Object Oriented PHP by Dr.C.R.Dhivyaa Kongu Engineering College
 
Python decorators
Python decoratorsPython decorators
Python decorators
 
Polymorphism.pptx
Polymorphism.pptxPolymorphism.pptx
Polymorphism.pptx
 
Python advance
Python advancePython advance
Python advance
 
Lecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptxLecture-10_PHP-OOP.pptx
Lecture-10_PHP-OOP.pptx
 
PHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptxPHP OOP Lecture - 03.pptx
PHP OOP Lecture - 03.pptx
 
Chap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.pptChap 3 Python Object Oriented Programming - Copy.ppt
Chap 3 Python Object Oriented Programming - Copy.ppt
 
OOC MODULE1.pptx
OOC MODULE1.pptxOOC MODULE1.pptx
OOC MODULE1.pptx
 
These questions will be a bit advanced level 2
These questions will be a bit advanced level 2These questions will be a bit advanced level 2
These questions will be a bit advanced level 2
 
Only oop
Only oopOnly oop
Only oop
 
Groovy presentation
Groovy presentationGroovy presentation
Groovy presentation
 
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptxINTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
INTRODUCTION TO OBJECT ORIENTED PROGRAMMING.pptx
 

Mais de Tanwir Zaman

Mais de Tanwir Zaman (16)

Cs3430 lecture 17
Cs3430 lecture 17Cs3430 lecture 17
Cs3430 lecture 17
 
Cs3430 lecture 15
Cs3430 lecture 15Cs3430 lecture 15
Cs3430 lecture 15
 
Cs3430 lecture 14
Cs3430 lecture 14Cs3430 lecture 14
Cs3430 lecture 14
 
Cs3430 lecture 13
Cs3430 lecture 13Cs3430 lecture 13
Cs3430 lecture 13
 
Cs3430 lecture 16
Cs3430 lecture 16Cs3430 lecture 16
Cs3430 lecture 16
 
Python lecture 12
Python lecture 12Python lecture 12
Python lecture 12
 
Python lecture 10
Python lecture 10Python lecture 10
Python lecture 10
 
Python lecture 09
Python lecture 09Python lecture 09
Python lecture 09
 
Python lecture 07
Python lecture 07Python lecture 07
Python lecture 07
 
Python lecture 06
Python lecture 06Python lecture 06
Python lecture 06
 
Python lecture 05
Python lecture 05Python lecture 05
Python lecture 05
 
Python lecture 04
Python lecture 04Python lecture 04
Python lecture 04
 
Python lecture 03
Python lecture 03Python lecture 03
Python lecture 03
 
Python lecture 02
Python lecture 02Python lecture 02
Python lecture 02
 
Python lecture 01
Python lecture 01Python lecture 01
Python lecture 01
 
Python lecture 11
Python lecture 11Python lecture 11
Python lecture 11
 

Último

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
AnaAcapella
 

Último (20)

How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.This PowerPoint helps students to consider the concept of infinity.
This PowerPoint helps students to consider the concept of infinity.
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptxBasic Civil Engineering first year Notes- Chapter 4 Building.pptx
Basic Civil Engineering first year Notes- Chapter 4 Building.pptx
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
Spellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please PractiseSpellings Wk 3 English CAPS CARES Please Practise
Spellings Wk 3 English CAPS CARES Please Practise
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 

Python lecture 8