43
1 Programming for Engineers in Python Autumn 2011- 12 Lecture 5: Object Oriented Programming

1 Programming for Engineers in Python Autumn 2011-12 Lecture 5: Object Oriented Programming

  • View
    221

  • Download
    1

Embed Size (px)

Citation preview

1

Programming for Engineers in

Python

Autumn 2011-12

Lecture 5: Object Oriented Programming

2

Lecture 4 Highlights

• Tuples, Dictionaries

• Sorting Lists

• Modular programming

• Data analysis: text categorization• Collect data

• Most frequent words

• How it is really done

3

Today• Quick review on functions• Object Oriented Programming (partially based on

chapters 15-18 in the book Think Python, available in the site)

4

Functions (Quick Overview)

5

How to Calculate 5! + 3! + 6!?

6

Problems• Same code duplicated 3 times• More elements more code duplicates• The program becomes longer and more

complicated• May cause bugs, cut & paste errors

• Hard to understand what was the writer’s intension

• What would we like?• Write the code once!

• Use it several times with different arguments

7

Solution - Functions

8

Functions

• A group of declarations and statements that is assigned a name • Effectively, a named statement block • Usually has a value

• A sub-program • Inside a fucntion we can call other functions

• Which can themselves use other functions, and so on…

• Function output: • Return value to the calling function

• If no value is to be returned, ‘None’ is returned

9

What are They Good For?

• Generalize a repeated set of instructions • We don’t have to keep writing the same thing over and

over• Solve bugs once…

• They can break your problem down into smaller sub-tasks • Easier to solve complex problems

• They make a program much easier to read and maintain• Abstraction – we don’t have to know how a function is

implemented to use it

10

In Short• Why do we need functions?

• Code reusability• Modularity• Abstraction

11

Examples

12

Passing Arguments to Functions

• When a function is called, arguments’ values are attached to function’s formal parameters by order, and an assignment occurs before execution

• Values are copied to formal parameters

13

Passing Arguments to Functions

• A reference is passed by reference• Example: lists• This explains why we can change an array’s

content within a function

456789a

14

Example

15

Pyhton Memory Model

• Stack: local variables and arguments, every function uses a certain part of the stack• Stack variables “disappear” when scope ends

• Heap: global variables and objects, scope independent• Garbage Collector

• Partial description

16

How to Change a Variable via Functions?

• So how can a method change an outer variable?• By its return value• By accessing heap-based memory (e.g., lists)

18

Lets Start Simpler

• How would you represent a library?• Container of books• Each book:

• Title

• Author

• ISBN number

• Number of pages

• Publisher

19

Printing a Book

20

What Would We Want?

• To group the definition of several variables under a single name – a new type

• Somewhat similar to functions…

• Using the new type as if it is part of the language: • Define variables, perform operation

21

Object-Oriented Programming (OOP)

• Represent problem-domain entities using a computer language

• When building a software in a specific domain, describe the different components of the domain as types and variables

• Thus we can take another step up in abstraction

22

Class as a BlueprintA class is a blueprint of objects

24

Classes as Data Types

• Classes define types that are a composition of other types and have unique functionality

• An instance of a class is named an object• Every instance may contain:

• Constructors• Attributes (data members / fields) • Methods

25

Car Example

• Members: 4 wheels, steering wheel, horn, color,…

• Every car instance has its own

• Methods: drive, turn left, honk, repaint,…

• Constructors: by color (only), by 4 wheels, engine,…

26

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 its advantages (to be apparent soon)

• class – a user defined type• How to represent a point?

27

Creating a new Point (instantiation)

blank is an instance of class Point

28

But Where is the Point?

• x does not exist “in” blank (nor y)• We want to be able to access x,y via

Point instance

29

Constructors

• A special function, defined in the class’s code that “produces” instances

• Invoked automatically when an object is instantiated• Given as input whatever is required to produce an

instance• What would a Point’s constructor accept as inputs?

30

Constructors – More Technically• Defined within the class’s scope• Always named __init__

• Short for initialization• 2 underscores init 2 underscores

• The first parameter would be self• To be explained later on• Note that when invoking (calling) the constructor, self is not

passed as an argument • It is common for the parameters of __init__ to have the same

names as the attributes

31

Attributes

• The variable p1 refers to a Point object• p1.x means “Go to object p1 refers to and get the value of x”

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

p1x 3.0y 4.0

Point

32

Instances and Functions• Objects can be passed as arguments to functions• Objects are mutable

33

Copying Objects

• is operator indicates that p1 and p2 are not the same object, the default behavior of the == operator is the same as the is operator

34

Instances as Return Values

35

A Circle• How would you represent a circle object?• Attributes?• Constructor?

36

Shallow / Deep Copy

37

Shallow / Deep Copy (Cont.)

38

Object Oriented Programming

• Programs are made of object definitions and function definitions, and most of the computation is expected in terms of operations on objects

• Each object definition corresponds to some object or concept in the real world, and the functions that operate on that object correspond to the ways real-world objects interact

39

Methods

• Method is a function that is associated with a particular class

• Examples in strings, lists, dictionaries, tuples• Difference between methods and functions:

• Methods are defined inside a class definition• The syntax for invoking a method• A method is called through an instance

40

Example: Distance Between Two Points (function)

41

Example: Distance Between Two Points (method)

42

Example: In Circle

43

Next week: defining a new type that behaves as part of the language

• More OOP• Implementation of Rational Numbers