Chapter 10 Object-Oriented
Programming (part 1)
In Chapter 6, we learned what objects are and how they are used. We found that all values
in Python are objects. Classes in object-oriented programming define objects. Thus, a class
is a “cookie cutter” for creating any number of objects of that type. As with functions, there
are predefined classes in Python, as well as the ability of programmers to define their own.
In this chapter, we see how to define and use classes in Python.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 1
Review of OO Programming
• Everything in real world is viewed as an object and every activity is
viewed as an interaction between objects
• Programming: represent real-world objects into software objects
– Real-world objects (e.g. bicycle) have
• states (speed, gear, direction) and behaviors (speedUp, changeGear, applyBrake)
– Software objects represent
• states with instance variables
(how to implement an instance variable: data structure)
• behaviors with instance methods (functions)
(how to implement an instance method: algorithm)
– Interaction between objects is made via method calls
– The same kind of objects is defined by a class
– We can create an object by “instantiating” a class
Abstract Data Type
• We can also view that real-world objects are instances of an
abstract data type (e.g., bicycle, car, student, shopping_cart), which
we implement via classes using data structures and algorithms
– Cf. programming language built-in data types such as string, int, float,
Boolean, list, …
Sketch of OO Programming Case
class Shopping_cart:
# l instance variables to implement shopping cart
def Shopping_cart(): # __intit__(self)
self.l = []
def add_item():
add_item() find_item()
def find_item(): Shopping_cart
… object data for x …
>> x = Shopping_cart()
>> x.add_item()
add_item() find_item()
>> y = Shopping_cart() Shopping_cart
>> y.add_item() … object data for y …
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 4
Three Features of OO Programming
• Encapsulation
No instance variables are accessible from outside and they are accessed only through
methods in the class (e.g., the list of a shopping-cart object is not accessed from outside)
• Inheritance
A class can be defined based on other classes (e.g., EE student class can be
defined using SNU student class)
Class hierarchy: car
/ | \
sedan suv van
|
• Polymorphism light van
Object of different subclasses can be treated as the same general superclass
Paradigm Shift by OO Programming
These three features of object-oriented programming
support a paradigm shift in software development:
• From the focus on variables and passing of variables to
functions in procedural (imperative) programming
• To the focus on objects and message passing between them
This makes software maintenance (유지, 보수, 관리) easier
Object-oriented programming languages such as Python, Java,
or C++ make OO programming more straightforward
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
6
Message passing occurs when a method of one object (or
main) calls a method of another. For example, if Object B
were a list and sort() a sorting method, then a call to sort()
by main is a message (or request) for it to become sorted.
A message to one object can result in the propagation of
messages among many other objects in order to accomplish
the request.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
7
What is a Class?
A class specifies the set of instance variables and instance
methods that are “bundled together” to define a type of object
• Also called member variables and member functions
• It also allows you to define your own type (abstract data type)
A class, therefore, is a “cookie cutter” or “blueprint” that can be
used to make as many object instances of that type object as
needed. For example, strings in Python are object instances of
the built-in String class.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
8
One method of the String class is isdigit(). Thus, every string
object has this method. The specific object whose isdigit()
method is called determines if its specific string is a digit
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
9
How to Define a Class? Member Variable
A class is defined as follows:
class MyClass:
body # body can be a single “pass” statement
Then, instantiate an object as follows:
instance = MyClass()
Example:
class Circle:
def __init__(self):
self.radius = 1 # radius is an instance variable of Circle
my_circle = Circle()
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
10
How to Define a Class? Member Variable
The class keyword is used to define classes, much as def is
used for defining functions.
All lines following the class declaration line are indented.
Instance variables are created and initialized in the __init__
special method. It has a special formal parameter, self, which
indicates the object itself (but it is not included as an actual
parameter when instantiating the object)
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 11
How to Define a Class? Member Variable
Object member variable can be accessed with . operator
my_circle = Circle()
print(2 * 3.14 * my_circle.radius)
my_circle.radius = 5
print(3.14 * my_circle.radius * my_circle.radius)
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
12
How to Define a Class? Member Function
class Circle:
def __init__(self, radius=1):
self.radius = radius
def area(self):
return self.radius * self.radius * 3.14159
Object member function can also be accessed with . operator
radius: 5
my_circle = Circle(5) my_circle
area()
print( my_circle.area() )
your_circle = Circle(10) radius: 10 your_circle
print( your_circle.area() ) area()
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
13
Encapsulation
Now, we see how to exploit encapsulation of OO programming
Encapsulation is a means of bundling together instance
variables and methods in a class to form an abstract data type.
If we move implementation details into methods, and users use
the class only thru methods, we say that we are practicing data
abstraction.
This allows information hiding, an important capability of OO
programming, which makes programs easier to maintain.
Let’s see an example of how this works
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 14
Adding Getter and Setter Methods
class Circle: c = Circle()
def __init__(self): print( c.radius )
self.radius = 1.0 c.radius = 2.0
def get_radius(self): versus
return( self.radius )
c = Circle() Practicing
def set_radius(self, r): print( c.get_radius() ) Data
Abstraction
self.radius = r c.set_radius(2.0)
Why practicing data abstraction?
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
15
Imaginary Instance Variable
class Circle: c = Circle()
def __init__(self): c.set_radius(2.0)
self.radius = 1.0 print( c.get_radius() )
def get_radius(self): c2 = Circle()
return( self.radius ) print( c2.get_diameter() )
c2.set_diameter(10.0)
def set_radius(self, r): …
self.radius = r
def get_diameter(self):
return( self.radius * 2.0 ) Now, we found that diameter accesses are
more frequent than radius accesses So,
def set_diameter(self, d): we decided to change class implementation
self.radius = d / 2.0
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
16
How Implementation change affect Usage?
class Circle: c = Circle()
def __init__(self): c.set_radius(2.0)
Practicing
self.diameter = 2.0 print(c.get_radius()) Data
Abstraction
def get_radius(self): c2 = Circle()
return( self.diameter/2.0 ) c2.set_diameter(10.0)
print(c2.get_diameter())
def set_radius(self, r):
self.diameter = r * 2.0 versus
def get_diameter(self): c = Circle()
return( self.diameter ) print(c.radius) print(c.diameter / 2.0)
c.radius = 2.0 c.diameter = 4.0
def set_diameter(self, d):
Need to change each usage 17
self.diameter = d
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
How to Enforce Data Abstraction?
class Circle: c = Circle()
def __init__(self): c.set_radius(2.0)
self.__diameter = 2.0 print(c.get_radius())
def get_radius(self): c2 = Circle()
return( self.__diameter/2.0 ) c2.set_diameter(10.0)
print(c2.get_diameter())
def set_radius(self, r):
self.__diameter = r * 2.0 c2.__diameter = 12.0 # error
def get_diameter(self):
Information hiding is enforced using
return( self.__diameter )
private members whose name starts
with __ (like __radious or __diameter)
def set_diameter(self, d):
self.__diameter = d
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
18
Benefit of Information Hiding
Objects communicate with one another only by well-defined,
public interfaces (which are methods, not instance variables).
They do not know (do not care to know and should not know)
how each object is implemented (what variables it has, with
what data structures those variables are implemented, etc)
Making programs easier to maintain
• Your programs become easier to reuse.
• You can easily augment what a class provides
• You can easily improve the way data are stored
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.1 What is Object-Oriented Programming?
19
Another Example: Fraction Class
Private instance variables: numerator (분자) and denominator (분모)
Public methods:
getNumerator(), getDenominator(),
setNumerator(), setDenominator()
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 20
Being private, instance
variables __numerator
and __denominator are
not meant to be directly
accessed.
In actuality, however,
private members are
accessible if written as
follows:
frac1._Fraction__numerator
for Fraction object frac1.
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation
frac1 = Fraction(4, 6) INSTANTIATE
Private Instance Variable Access
frac1.__numerator = 4 ACCESS NOT ALLOWED
frac1.__denominator = 6 ACCESS NOT ALLOWED
Public Method Access
frac1.getNumerator() ACCESS ALLOWED
frac1.getDenominator() ACCESS ALLOWED
frac1.setNumerator(4) ACCESS ALLOWED
frac1.setDenominator(6) ACCESS ALLOWED
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 22
Private members of a class begin with two underscore
characters, and should not be directly accessed by the
methods of any other class. Public members of a class, on
the other hand, are directly accessible by others
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 23
Getters and Setters
The method below are referred to as getters and setters (or
readers and writers) since their purpose is to get (return) and set
(assign) private instance variables of a class.
Restricting access to instance variables via getter and setter
methods allows control over how they are assigned and retrieved.
frac1.getNumerator()
frac1.getDenominator()
frac1.setNumerator(4)
frac1.setDenominator(6)
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 24
Name Mangling of Private Members
Actually, how to restrict private member variables (or methods)?
All private class members are automatically renamed to begin
with a single underscore character followed by the class name.,
which is called name mangling
frac1._Fraction__numerator
Unless the variable or method is accessed with its complete
(mangled) name, it will not be found. Name mangling prevents
unintentional access of private members of a class, while still
allowing access when needed.
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 25
Let’s Try It
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 26
Self Parameter of Methods in Python
The methods of a class are essentially functions meant
to operate on the instance variables of the class.
In Python, functions serving as a method must have an
extra first parameter, by convention named self. This
parameter contains a reference to the object instance to
which the method belongs.
When a method accesses any other member of the
same class, the member name must be preceded by
'self' (e.g., self.__numerator).
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 27
Special Methods in Python
Method names that begin and end with two underscore
characters are called special methods in Python. Special
methods are automatically called.
For example, the __init__ method of the Fraction class
developed is automatically called whenever a new
Fraction object is created,
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 28
The values in parentheses are arguments to the __init__
method to initialize a new Fraction object to a specific
value. Note that although there are three parameters
defined (self, numerator, denominator), the first
argument is always implied. Therefore, only the
remaining arguments (numerator and denominator) are
explicitly provided when creating a Fraction object.
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 29
Two other special methods of Python are __str__ and
__repr__. These methods are used for representing the
value of an object as a string.
The __str__ method is called when an object is displayed
using print (and when the str conversion function is
used.) The __repr__ function is called when the value of
an object is displayed in the Python shell (when
interactively using Python).
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 30
The difference in these special methods is that __str__ is
for producing a string representation of an object’s value
that is most readable (for humans), and __repr__ is for
producing a string representation that Python can
evaluate. If special method __str__ is not implemented,
then special method __repr__ is used in its place.
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 31
An implementation of __repr__ for the Fraction class is
given below,
This, therefore, will display Fraction values as we
normally write them:
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 32
Arithmetic Operators in Python
How can we provide a method that adds two fractions
and returns a result fraction object? Define add method:
class Fraction():
…
def add(self, rfrac):
numer = …
denom = …
result_frac = Fraction(numer, denom)
return result_frac
x = Fraction(5,3)
y = Fraction(4,7)
z = x.add(y) #z=x+y
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 33
Arithmetic Operators in Python
Python provides special methods to class that allows
using (more intuitive) arithmetic operators given below.
The expression frac1 + frac2, for example, evaluates to
the returned value of the __add__ method in the class,
where the left operand (frac1) is the object on which the
method call is made: frac1.__add__(frac2).
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 34
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 35
The Fraction type developed represents the power of
abstraction, implemented through the use of encapsulation.
The Fraction class contains two integer instance variables and an
associated set of methods. That is what it “really” is.
Through the use of information hiding, however, the client is
provided an abstract view which, for all intents and purposes, is
a Fraction type. That is, you defined your own abstract data type
Intoduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 10.2 Encapsulation 36