0% found this document useful (0 votes)
3 views40 pages

ch06 Part1

Chapter 6 discusses the fundamentals of object-oriented programming (OOP) in Python, highlighting how objects serve as the primary building blocks, contrasting with functions in imperative programming. It explains the concept of objects, their attributes and methods, and how they represent real-world entities, emphasizing the significance of references in memory management and the distinction between shallow and deep copies of objects. The chapter also covers the historical context of OOP's development and its impact on modern programming practices.

Uploaded by

김우석
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views40 pages

ch06 Part1

Chapter 6 discusses the fundamentals of object-oriented programming (OOP) in Python, highlighting how objects serve as the primary building blocks, contrasting with functions in imperative programming. It explains the concept of objects, their attributes and methods, and how they represent real-world entities, emphasizing the significance of references in memory management and the distinction between shallow and deep copies of objects. The chapter also covers the historical context of OOP's development and its impact on modern programming practices.

Uploaded by

김우석
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Chapter 6 Objects and Their Use

In imperative programming, functions are the primary building blocks of program design.

In object-oriented programming, objects are the fundamental building blocks in which


functions (methods) are a component.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 1
Motivation
Python is an object-oriented (OO) programming language

>>> l = [20, 10, 40, 30]


>>> l.sort()

>>> m = [10, 20, 30, 40]


>>> m.reverse()

l.sort() or m.reverse() is a typical way of OO programming

What is object-oriented programming?


Compare to procedural language like C

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 2
Idea of Objects
The idea of incorporating “objects” into a programming language came out of
work in computer simulation. Given the prevalence of objects in the world, it
was natural to provide the notion of an object within simulation programs that
simulate some aspect of the world.

In the early 1970s, Alan Kay at Xerox PARC (Palo Alto Research Center) fully
evolved the notion of object-oriented programming with the development of a
programming language called Smalltalk. The language became the inspiration for
the development of graphical user interfaces (GUIs) — the primary means of
interacting with computer systems today. Before that, all interaction was
through typed text. In fact, it was a visit to Xerox PARC by Steve Jobs of Apple
Computers that led to the development of the first commercially successful GUI-
based computer, the Apple Macintosh in 1984. In this chapter, we look at the
creation and use of objects in Python.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 3
Some Commonly-Used Programming Languages

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons 4
What is Programming?
• It is for modelling (simulating) a real world on a computer
• We can model real world by mimicking what computer H/W does
– Memory (variables, lists, other data structures) and Computing Processor
– Repeat the followings
• Read from memory, Compute, Write intermediate results into memory
– Achieve the real-word modelling as a side effect
• For example, implement a mathematical set using a list
• This is what procedural programming does
– But, is this what is really happening in real world (e.g., set, car
simulation, shopping cart)? No, we need more abstraction
Object-Oriented Programming
• Everything in real world is viewed as an object and every activity
is viewed as an interaction between objects
• Representing real-world objects into software objects
– Real-world objects (e.g. cars) have states (current states of gear,
speed, direction, etc) and behaviors (start, break, turn, pass)
– Software objects represent states with instance variables and
behaviors with methods (functions)
– Interaction between objects is made via method calls
– The same sort of objects is defined by a class, a new abstract data
type (e.g., car, set, shopping cart)
– We can create an object by “instantiating” a class
An OO Programming Case
class Car:
def Car(): // states or attributes
self.gear = ;
self.speed = ;
self.dir =;
….
def start() {gear = 1; dir = Direction(north); set-speed(..); …..}
def set-speed(int y) { speed = y;… }
def get-speed() { return speed;… }
def turn(Direction x) { dir = x; }
def pass(Car c) {set-speed( c.get-speed() + 20 ); … } x
} gear speed dir
start(), set-speed() y
turn(), pass()
main() {
gear speed dir
x = Car(); y = Car(); z= Car(); start(), set-speed()
x.start(); x. set-speed(60); y.start(); y.set-speed(60); turn(), pass()

y.pass(x);….
} Main()
Software Objects in Python

Objects are the fundamental component of object-oriented


programming. Although we have not yet stated it, all values
in Python are represented as objects. This includes, for
example, lists, as well as numerical values.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 8
What is an Object?

An object contains a set of attributes (states), stored in a set


of instance variables, and a set of functions called methods
that provide its behavior.

List in Python is actually an object

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 9
When sorting a list in procedural programming, there are two
distinct entities — a sort function and the list to pass it to.
names_list = [Johnson, Chen, Barlow …]

def sort( l ):
….

sort( names_list )

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 10
In object-oriented programming, the sort routine would be
part of the object containing the list.
names_list

All list objects contain the same set of methods. Thus, names_list
is sorted by simply calling that object’s sort() method,
names_list.sort()

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 11
names_list.sort()

The period . is referred to as the dot operator, used to select


a member of an object. In this case, a method sort() is
selected.

Note that no arguments are passed to the method. This is


because methods operate on the data of the object that they
are part of. Thus, the sort method does not need to be told
which list to sort. Calling the method is more of a message
saying “sort yourself.”

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 12
Suppose there was another list object called part_numbers,
containing a list of automobile part numbers.
part_numbers = [PJK2400, LGH22, GK4592, …]
part_numbers

Since all list objects behave the same, part_numbers would


contain the identical set of methods as names_list. Only the
data that they operate on would be different.
part_numbers.sort()
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 13
Object-Oriented Programming

If we convert shopping_cart programming in OO fashion, we


can create a shopping cart object, and perform add_item(),
remove_item(), find_item(),…, on the shopping cart object:
x = Shopping_cart() add_item() find_item()
x.add_item() Shopping_cart
… object data for x …
x.find_item()

y = Shopping_cart()
add_item() find_item()
y.add_item()
Shopping_cart
… object data for y
… …
More on later in chapter 10.
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 14
Object References

We look at how objects (values) are represented and the


effect it has on the operations of assignment and
comparison, as well as parameter passing of objects.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 15
References in Python

In Python, objects are represented as a reference to an object


in memory.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 16
A reference is a value that references, or “points to,” the location
of another entity. (Similar to a “pointer” in C)

When a new object in Python is created, two values are stored in


Python VM: the object, and a variable holding a reference to the
object. All access to the object is through the reference value.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 17
The value that a reference points to is called the dereferenced
value. This is the value that the variable represents.

We can get the reference value of a variable (the location in


which the dereferenced value is stored) by use of built-in
function id.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 18
>>> id(n) >>> id(k) >>> id(s)
505498136 505498136 505498296

We see that the dereferenced values of n and k, 10, is stored in


the same memory location (505498136), whereas the
dereferenced value of s (505498296), 20, is stored in a different
location.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 19
Even though n and k are separately assigned literal value 10,
they reference the same instance of 10 in memory (505498136).
We would expect that two instances of the value 10 be stored.

Python is being clever here. Since integer values are immutable,


it assigned both n and k to the same instance. This saves
memory and reduces the number of reference locations that
Python must maintain. From the programmer’s perspective
however, they can be treated as if each holds its own instance.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 20
Let’s Try It

From the Python Shell, enter the following and observe the results.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 21
The Assignment of References

Consider what happens when one variable, n, is assigned to


another, k, depicted below.

When variable n is assigned to k, it is the reference value of k


that is assigned, not the dereferenced value 20.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 22
To verify that two variables refer to the same object instance,
we can compare their id values using the comparison operator.

We can also verify this by use of the is operator, which performs


id(k) == id(n).

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 23
When variables n and k were separately assigned the value 20,
each ended up referring to the same instance of 20 in memory
because integer values are immutable, and Python decided to
have both variables share the same instance.

>>> k = 20
>>> n = 20

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 24
When variable n was directly assigned to k, both variables
ended up referring to the same instance of 20 in memory
because assignment in Python assigns reference values, and not
the dereference values.

>>> k = 20
>>> n = k

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 25
If one of the two variables is assigned a new value, then they
would no longer reference the same memory location.

>>> k = 30

30

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 26
Memory Deallocation and Garbage Collection

Consider what happens when a variable n is assigned a new value,


40, and no other variable references the original value 20.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 27
After n is assigned to 40, the memory location storing integer
value 20 is no longer referenced — thus, it can be deallocated.

To deallocate a memory location means to change its status


from “currently in use” to “available for reuse.”

In Python, memory deallocation is automatically performed by a


process called garbage collection (by Python VM)

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 28
Garbage collection is a method of automatically determining
which locations in memory are no longer in use, and
deallocating them.

The garbage collection process is ongoing during the execution


of a Python program.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 29
List Assignment and Copying
Now that we understand the use of references in Python, we
can revisit the discussion on creating and copying lists (ch 4)

list1 = [10, 20, 30]


More precisely
will create list1 10 list1 10
20 20
30
30

If we do

list2 = list1
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 30
When a variable is assigned to another variable referencing a
list, each variable ends up referring to the same instance of
the list in memory.

Thus, any change to the elements of list1 will result in changes


to list2.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 31
We also learned that a copy of a list can be made as follows.

list() is referred to as a list constructor. The result of the


copying is depicted below.

Since a copy of the list structure has been made, changes to


the elements of one list will not result in changes to the other.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 32
The situation is different if the list contains sub-lists, however.

Below is the resulting list structure after this assignment.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 33
Although copies were made of the top-level list structures, the
elements within each list were not copied. This is referred to as
a shallow copy.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 34
If a top-level element of one list is reassigned, for example
list1[0] = [70, 80], the other list would remain unchanged.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 35
If, however, a change to one of the sub-lists is made, for
example, list1[0][0] = 70, the corresponding change would be
made to the other list as well. Thus, list2[0][0] would also be
equal to 70.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 36
A deep copy operation of a list (structure) makes a copy of the
complete structure, including sub-lists.
(Since immutable types cannot be altered, immutable parts of
the structure may not be copied.)

Such an operation can be performed with the deepcopy


method of the copy module,

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 37
The result of this form of copy is shown below.

As a result, the reassignment of any part (top level or sublist) of


one list will not result in a change in the other

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 38
Let’s Try It
From the Python Shell, enter the following and observe the results.

Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 39
>>> l1=[10, 20, [30]]
>>> l2=copy.deepcopy(l1)
>>> id(l1[0])
1432541504
>>> id(l2[0])
1432541504
>>> id(l1[2])
53204992
>>> id(l2[2])
57047120

>>> l1 = [40, 20, (100,)]


>>> l2=copy.deepcopy(l1)
>>> id(l1[2])
57305840
>>> id(l2[2])
57305840
Introduction to Computer Science Using Python – Dierbach Copyright 2013 John Wiley and Sons Section 6.1 Software Objects 40

You might also like