Transcript The Scala Experience Safe Programming Can be Fun!
Programming for Engineers in Python
Lecture 5: Object Oriented Programming
Autumn 2011-12
1
Lecture 4 Highlights • Tuples, Dictionaries • Sorting Lists • Modular programming • Data analysis: text categorization • Collect data • Most frequent words • How it is really done 2
Today • Quick review on functions • Object Oriented Programming (partially based on chapters 15-18 in the book Think Python, available in the site) 3
Functions (Quick Overview) 4
How to Calculate 5! + 3! + 6!?
5
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 6
Solution - Functions 7
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 8
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 9
In Short • Why do we need functions?
• Code reusability • Modularity • Abstraction 10
Examples 11
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 12
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 a 4 5 6 7 8 9 13
Example 14
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 15
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) 16
A Car • How would you represent a car?
• Parts / features: 4 wheels, steering wheel, horn, color,… • Functionality: drive, turn left, honk, repaint,… • In Python???
17
Lets Start Simpler • How would you represent a library?
• Container of books • Each book: • Title • Author • ISBN number • Number of pages • Publisher 18
Printing a Book 19
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 20
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
21
Class as a Blueprint A
class
is a blueprint of
objects
22
Class as a Blueprint A
class
is a blueprint of
objects
23
Classes as Data Types • Classes define types that are a
composition
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 of 24
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,… 25
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?
26
Creating a new Point (instantiation) blank is an
instance
of class Point 27
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 28
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?
29
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 30
Attributes p1 Point x y 3.0
4.0
• 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 31
Instances and Functions • Objects can be passed as arguments to functions • Objects are mutable 32
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 33
Instances as Return Values 34
A Circle • How would you represent a circle object?
• Attributes?
• Constructor?
35
Shallow / Deep Copy 36
Shallow / Deep Copy (Cont.) 37
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 38
Methods •
Method
class is a function that is associated with a particular • 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 39
Example: Distance Between Two Points (function) 40
Example: Distance Between Two Points (method) 41
Example: In Circle 42
Next week: defining a new type that behaves as part of the language • More OOP • Implementation of Rational Numbers 43