0% found this document useful (0 votes)
12 views28 pages

Lec 6

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)
12 views28 pages

Lec 6

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
You are on page 1/ 28

OBJECT-ORIENTED

PROGRAMMING 1
CS5800: Lecture 6

1
LEARNING OBJECTIVES

OOP concepts
Creating objects
Class attributes, methods
Querying types
Special methods

2
RECAP: FUNCTIONS

Means to achieve abstraction, decomposition and


reuse
Function scope: data manipulated by the function
◦ New scope is created/disbanded every time a function
is called/returns
Abstract behaviour, but not data
◦ All local data is lost once function returns
◦ Global variables offer a partial solution, but leak
abstraction
Objects & types: a principled way to bundle data and
behaviour

3
OBJECTS AND DATA TYPES

Python supports many different kinds of objects


1234 3.14159 "Hello" [1, 5, 7, 11, 13]
{"CS": "Computer Science", "PH": "Physics"}
Objects have types
◦ 1234 is an instance of int object type
◦ "Hello" is an instance of a string (str) object type
Object types define
◦ Data attributes: other objects that make up the type
◦ Set of operations for interaction with the objects of
this type

4
OBJECT-ORIENTED
PROGRAMMING (OOP)

Everything in Python is an object and has a type


Objects are abstractions that capture
◦ Internal representation through data attributes
◦ Interface for interacting with objects through methods
(operations), defines behaviour but hides implementation
Can create new instances of objects
Can destroy objects
◦ Explicitly through del
◦ Python runtime reclaims destroyed and inaccessible
objects through garbage collection

5
PYTHON OBJECT TYPES

Some object types are built-in in Python:


◦ lists: [1, 2, 3, 4]
◦ tuples: (1, 2, 3, 4)
◦ strings: 'abcd'

Supports creating our own data types

6
EXAMPLE: [1, 2, 3, 4]
L = [1, 2, 3, 4] is of type list
Internal representation: linked list of cells

1 2 3 4
Follow pointer to
Interface to manipulate lists: the next index
◦ L[i], L[i:j], +
◦ len(), min(), max(), del(L[i])
◦ L.append() ,L.extend(), L.count(), L.index(),
L.insert(), L.pop(), L.remove(), L.reverse(), L.sort()

Internal representation should be private


Must be manipulated through defined interface - to
ensure correct behaviour is not compromised
7
Go to Moodle quiz ‘Internal interfaces’
CREATING AND USING YOUR OWN
DATA TYPES WITH CLASSES
Make a distinction between creating a class and using an
instance of the class
◦ Class defines an object type, object is an instance of a class
Creating a class:
◦ defining the class name
◦ defining class attributes
◦ e.g., someone wrote a code to implement list class

Using the class:


◦ creating new instances of objects
◦ doing operations on the instances
◦ e.g., L=[1,2] and len(L)

9
DEFINE YOUR OWN OBJECT TYPE

Use the class keyword to define new type


class Coordinate(object):

class definition name/type class parent

Followed by the definition of class attributes in an


indented code block
The word object means that Coordinate is a Python
object and inherits all its attributes
◦ Coordinate is a subclass of object
◦ object is a superclass of Coordinate
◦ Parent class defaults to object if omitted

10
WHAT ARE CLASS ATTRIBUTES?

Data and operations that “belong” to the class


Data attributes
◦ think of data as other objects that make up the class
◦ e.g., a coordinate is made up of two numbers
Methods (operational attributes)
◦ Functions that only valid within the context of this class
◦ How to interact with the object
E.g., distance between two coordinate objects makes
sense but distance between two list objects does not

11
Go to Moodle quiz ‘Internal attributes’
DEFINING HOW TO CREATE AN
INSTANCE OF A CLASS

Start by defining how to create an instance of


object
Use a special method called __init__ to
initialise some data attributes
data to initialise
class Coordinate(object): the Coordinate
object attributes
def __init__(self, x, y):
special method to with
create an instance self.x = x
__ is double
underscore
self.y = y
parameter referring
to an instance of
two data attributes the class
for every Coordinate
object
13
CREATING AND USING AN
INSTANCE OF A CLASS
c = Coordinate(3,4) create a new object of
type Coordinate and pass
origin = Coordinate(0,0) in 3 and 4 to the __init__()

print(c.x, origin.x)
use "dot" to access the
object attribute

Data attributes of an instance are called instance


variables
Don’t provide argument for self, Python does this
automatically

14
WHAT IS A METHOD?

Operational attribute, like a function that works


only with this class scope
Python always passes the object as the first
argument
◦ Convention is to use self as the name of the first
argument of all methods
The “.” operator is used to access any attribute
◦ a data attribute of an object
◦ a method of an object

15
Go to Moodle quiz ‘Create class’
DEFINE A METHOD FOR THE
Coordinate CLASS
class Coordinate(object): Refers to any
def __init__(self, x, y): instance
self.x = x Another parameter
of to method
self.y = y
def distance(self, other): Dot notation to
x_diff_sq = (self.x - other.x)**2 access data
y_diff_sq = (self.y - other.y)**2 attributes
return (x_diff_sq + y_diff_sq)**0.5

Other than self and dot notation, methods behave


just like functions (take params, do operations,
return)

17
TWO WAYS OF USING A METHOD

c = Coordinate(3,4) c = Coordinate(3,4)
origin = Coordinate(0,0) origin = Coordinate(0,0)
print(c.distance(origin)) print(Coordinate.distance(c, origin))

Object to call Parameters not Parameters,


Name of
method on including self including the
class
(implied to be c) object to call the
method on,
Name of Name of representing self
method method

18
Go to Moodle quiz ‘Create method’
PRINT REPRESENTATION OF AN
OBJECT
>>> c = Coordinate(3,4)
>>> print(c)
<__main__.Coordinate object at 0x10aa29780>

Uninformative print representation by default


Can define a __str__() method for a class
Python calls the __str__ method whenever an
object is represented as a string
◦ e.g., str(c), print(c), etc.

Allows you to choose your own way to "stringify"


the object

20
DEFINING YOUR OWN STRING
REPRESENTATION
class Coordinate(object): >>> c = Coordinate(3, 4)
def __init__(self, x, y): >>> print(c)
self.x = x <3,4>

self.y = y
def distance(self, other):
x_diff_sq = (self.x-other.x)**2
y_diff_sq = (self.y-other.y)**2
return (x_diff_sq + y_diff_sq)**0.5
def __str__(self):
return "<" + str(self.x) + "," + str(self.y) + ">"

Must return a string


Name of
special method
21
QUERYING TYPES AND CLASSES
Get the type of an object
>>> c = Coordinate(3, 4)
>>> print(c)
(3, 4)
>>> print(type(c))
<class '__main__.Coordinate'>
and the type of a class
>>> print(Coordinate)
<class '__main__.Coordinate'>
>>> print(type(Coordinate))
<class 'type'>
Use isinstance() to test if an object is of a specific type:
>>> print(isinstance(c, Coordinate))
True

22
SPECIAL METHODS
SPECIAL OPERATORS
+, -, ==, <, >, len(), str(), etc.
+, -, ==, <, >, len(), print, and many
◦ https://docs.python.org/3/reference/
others
datamodel.html#basic-customization
https://docs.python.org/3/reference/datamodel.html#basic-customization
Canprint,
like overridecan
these to work
override with
these toyour
workclass
with your class
Definethem
define themwith
withdouble
double underscores
underscoresbefore/after
before/after
__add__(self, other) self + other
__sub__(self, other) self - other
__eq__(self, other) self == other
__lt__(self, other) self < other
__len__(self) len(self)
__str__(self) print self
... andhttps://docs.python.org/3/library/operator.html
See others
23
Go to Moodle quiz ‘Special methods’
EXAMPLE: FRACTIONS

Create a new type to represent a number as a


fraction
Internal representation is two integers
◦ numerator
◦ denominator
Interface:
◦ convert to string, float, invert the fraction
◦ add, subtract

25
IMPLEMENTING USING
THE CLASS vs THE CLASS
write code from two different perspectives
implementing a new using the new object type in
object type with a class code
• define the class • create instances of the
• define data attributes object type
(WHAT IS the object) • do operations with them
• define methods
(HOW TO use the object)

6.0001 26
LECTURE 9 3
CLASS DEFINITION INSTANCE
OF AN OBJECT TYPE vs OF A CLASS
class name is the type instance is one specific object
class Coordinate(object) coord = Coordinate(1,2)

class is defined generically data attribute values vary


• use self to refer to some between instances
instance while defining the c1 = Coordinate(1,2)
class c2 = Coordinate(3,4)
(self.x – self.y)**2 • c1 and c2 have different data
• self is a
parameter to attribute values c1.x and c2.x
methods in class definition because they are different
objects
class defines data and instance has the structure of
methods common across all the class
instances
6.0001 LECTURE 9 4
27
Go to Moodle quiz ‘Fractions’

You might also like