Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented...

43
Lecture 8: Object-Oriented Programming 1 1 Introduction to Programming with Python

Transcript of Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented...

Page 1: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Lecture 8:

Object-Oriented Programming 1

1

Introduction to Programming

with Python

Page 2: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

• How would we implement a software system for

managing students’ grades that way?

• By this approach, data is usually being stored in global data

structures and accessed by many different functions.

Procedural Programming

• Up until now, we only used

functions to organize our code into

modular code blocks.

• Why is this important ?

2

Page 3: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Object-Oriented Programming

• In Object Oriented Programming, we model the

entities of the real world using objects.

3

Page 4: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Object-Oriented Programming

• In Object Oriented Programming, we model the

entities of the real world using objects.

• Objects holds both code (functions) and data for the

entities they represent.

4

Page 5: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Object-oriented programming ( מונחה עצמיםתכנות ) involves

programming using objects.

An object (עצם ) represents an entity in the real world that can

be distinctly identified.

For example: a student, a desk, a circle, a button can all be

viewed as objects.

An object has a unique identity ( ייחודיתזהות ), state, and

behaviors.

The state (מצב) of an object consists of a set of data fields

(also known as properties) with their current values.

The behavior of an object is defined by a set of (התנהגות)

methods.

Object-Oriented Programming concepts

5

Page 6: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Objects - examples

Student – properties ?Robot - properties Lecturer – properties ?

6

Page 7: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

An object has : - unique identity ( זהות ייחודית )

- state ( מצב )

- behaviors ( התנהגות )

• state(attributes) consists of a set of data fields

(properties) with their current values.

• behavior(operations) of an object is defined by a set

of methods.

data field 1

method n

data field m

method 1

(A) A generic object

...

...

State

(Properties)

Behavior

radius = 5

findArea()

Data field, State

Properties

Method,

Behavior

(B) An example of circle object

7

Page 8: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Classes - definitions• In the real world, you'll often find many individual objects all

of the same kind. There may be thousands of other bicycles in existence, all of the same make and model.

• Each bicycle was built from the same set of prototype( (אבטיפוס and therefore contains the same components.

• In object-oriented terms, we say that your bicycle is an instance (מופע) of the class (מחלקה) of objects known as bicycles. A class is the prototype from which individual objects are created.

8

Page 9: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

• Classes :examples (מחלקות)

– People, books, dogs, cats, cars, airplanes, trains,etc.

• Instance of a class (מופע של מחלקה)

– You, your parents, the book you are reading, the car you drive

Example: Car class :

Property names Method Names

model startEngine

year stopEngine

Color accelerate

Classes - examples

9

Page 10: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Instance of a class

A class is used to define an object.

The state (consists of a set of data fields) defines the object,

and the behavior defines what the object does.

Class Name: Student

Data Fields:

name is _______

Methods:

takeCourse

Student Object 1

Data Fields:

name is Kerem

Student Object 2

Data Fields:

name is Onur

Student Object 3

Data Fields:

name is Meltem

A class template

Three objects of

the Student class

David Ronit Vered

Instances of the class Student

10

Page 11: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Instance of a class - example

11

Page 12: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

12

Object-Oriented Programming

Wikipedia:

An object-oriented program may be viewed

as a collection of interacting objects, as

opposed to the conventional model, in which a

program is seen as a list of tasks (subroutines)

to perform.

12

Page 13: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Characteristics of the

Object-Oriented Paradigm

13

Page 14: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Example: An object that represents

a Student

14

Data: Attributes (==Variables/Fields)

Functionality: Methods (==Functions)

Page 15: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Classes are user-defined types

• In OOP, a Class is a piece of code that defines

a new object type.

• A class defines which attributes (fields) will be

allocated in memory for each object (instance) of

the class.

• A class contains the code for the functions

(methods) of a given object type.

• Classes can viewed as a blueprint for creating

objects.

15

Page 16: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Classes and Objects

• A class defines a new type of which many

objects (instances) can be created.• Each object may hold different values for the class fields.

16

Page 17: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

18

Classes as Data Types

Classes define types that are:

• a composition of other types

• have unique functionality

Every class may contain:

• Attributes (fields)

• Methods

• Constructor (Initialization function)

Page 18: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

20

Classes in Python

• Class definition looks like this:

class ClassName:

"""documentation string"""

def __init__(self):

# constructor

def method_name(self, arg1, arg2):

# method code

Page 19: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

21

How to Represent a Point in 2D?

Alternatives

• Two variables x, y

• Elements in a list / tuple

• A new data type

Creating a new type is a (little) more complicated,

But has advantages (to be apparent soon)

So - How should we represent a point?

Page 20: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

In the shell:

What happens if we try:

?

22

Creating a new Point (instantiation)

blank is an instance of a point

Later!

Page 21: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

23

But Where is the Point?

• Currently, blank does not hold any data, so x does not exist (nor does y)

• We want to be able to initialize and access x, y via Point instance

Page 22: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Object initialization

• There are two ways to initialize an object:

• Explicitly

• Using a constructor, which is a special function in

charge of initializing the object’s variables

24

Page 23: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

25

Constructors

• Definition in the class’ code that “produces” instances

• Invoked automatically when an object is created

• Input: whatever is required to produce a new instance

• What would a Point constructor accept as input?

Page 24: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

26

Constructors – More Technically

Definition within the class’s scope:

• Always named __init__

• 2 underscores, followed by the word init, followed by 2 more underscores.

• The first parameter is self

• A reference to the particular current instance of the class.

• When calling the constructor, self should not be passed, it is created by Python.

• Default constructor - If a constructor was not implemented for a class, Python assumes that the class has a default empty constructor (no arguments, no attribute initialization)

Page 25: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

27

Attributes

• The variable p1 refers to a Point object

• p1.x means “get the value of x from object p1”

• There is no conflict between a variable x and the attribute x

p1x 3.0

y 4.0

Point>>> p1 = Point(3.0, 4.0)

>>> p1.x

3.0

>>> p1.y

4.0

>>> x = p1.y

>>> print(x)

4.0

>>> print(p1.x)

3.0

Page 26: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

28

Instances and Functions

Objects can be passed as arguments to functions:

>>> print_point(p1)

< 3.0 , 4.0 >

Objects are mutable:

>>> move_point(p1, 2, -1)

>>> print_point(p1)

< 5.0 , 3.0 >

Will now “print(p1)”

work?

Next week!

Page 27: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

29

Instances and Functions

Objects can be returned by functions:

0 2.0)

Page 28: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

30

Object Oriented Programming

Programs are made of

- object definitions

- function definitions

Most of the computation is in operations on objects

An object definition corresponds to objects or concepts in the real world.

The functions that operate on those objects correspond to the ways real-world objects interact.

Page 29: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

31

Methods

Method

a function that is associated with a particular class.

Examples in strings, lists, dictionaries, tuples:

list.append(), str.upper(), dict.items()

Difference between methods and functions:

• Methods are defined inside a class definition

• The syntax for invoking a method is different:

• A method is called through an instance

Page 30: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Methods

class New_Class:

"""documentation string""“

def __init__(self, att1):

self.att1 = att1;

def method_name(self, arg1, arg2):

do_something_with(self.att1,arg1,arg2)

32

1. The first argument of each method is self. it’s not passed as an

argument in the call – self is actually a reference to the object that

invoked the method.

2. Access the attributes of the class – only with self.

Page 31: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

33

Example: Distance Between Two

Points (as a method)

Page 32: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

34

Example: Distance Between Two

Points (method vs. function)

…….

Method call

Function call

…….

Page 33: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

35

A Circle

• How would you represent a circle object?

• Attributes:

• center (Point)

• radius (int/float)

• Methods:

Method name description arguments return value

__init__ The constructor Center(Point),

radius(int/float)

-

print_circle Prints circle - -

in_circle Checks if a point is

located inside the

circle

a point object True/False

Composition of other

user defined types

Page 34: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

36

A Circle

Next week – make str(center) work!

Page 35: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

37

Example: In Circle

…..

Point.distance method call Boolean value

Page 36: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

38

Code – Define Classes

….

….

Page 37: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

39

A Rectangle (design options)

How would you represent a rectangle?

For simplicity ignore angle, assume the rectangle is vertical or horizontal

Several possibilities:

• Two opposing corners

• One corner + width and height

Page 38: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Rectangle - Design

• Attributes:

• width (int/float)

• height (int/float)

• corner (Point)

• Methods

40

Method name description arguments return value

__init__ The constructor width, height, corner -

print_rec Prints the rectangle - -

get_center Returns the center

of the rectangle

- A Point object that

represents the

center.

Page 39: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

41

A Rectangle - Implementation

Page 40: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

42

Find Center

Page 41: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Polymorphism

Definition

Objects of various types define a common

interface of operations for users.

43

Page 42: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

Polymorphism - Example

class Cat:

def talk(self):

return 'Meow!'

class Dog:

def talk(self):

return 'Woof! Woof!'

animals = [Cat(), Dog()]

for anim in animals:

print( anim.talk() )

Meow!

Woof! Woof!

Page 43: Introduction to Programming with Pythonipp201/wiki.files/V-Lecture 8 - OOP1.pdf · Object-oriented programming (םימצע החנומ תונכת) involves programming using objects.

is and ==

45

is will return True if two variables point to the same object.

== will return True if the objects referred to by the variables are equal

>>> a = [1, 2, 3]

>>> b = a

>>> b is a

True

>>> b == a

True

>>> b = a[:]

>>> b is a

False

>>> b == a

True

1 2 3

a b

1 2 3