SlideShare a Scribd company logo
Objects
Lecture 9
Announcements for Today
Assignment 1
• We have finished grading
• Resubmit until correct
§ Read feedback in CMS
§ Reupload/request regrade
• If you were very wrong…
§ You received an e-mail
§ More 1-on-1s this week
• Finish Survey 1
Assignment 2
• Posted last Friday
§ Written assignment
§ Do while revising A1
§ Relatively short (2-3 hrs)
• Due Thursday
§ Submit as a PDF
§ Scan or phone picture
§ US Letter format!
9/20/22 Objects 2
The Basic Python Types
• Type int:
§ Values: integers
§ Ops: +, –, *, //, %, **
• Type float:
§ Values: real numbers
§ Ops: +, –, *, /, **
• Type bool:
§ Values: True and False
§ Ops: not, and, or
• Type str:
§ Values: string literals
• Double quotes: "abc"
• Single quotes: 'abc'
§ Ops: + (concatenation)
9/20/22 Objects 3
Are the the only
types that exist?
Example: Points in 3D Space
def distance(x0,y0,z0,x1,y1,z1):
"""Returns distance between points (x0,y0,y1) and (x1,y1,z1)
Param x0: x-coord of 1st point
Precond: x0 is a float
Param y0: y-coord of 1st point
Precond: y0 is a float
Param z0: z-coord of 1st point
Precond: z0 is a float
….
"""
• This is very unwieldy
§ Specification is too long
§ Calls needs many params
§ Typo bugs are very likely
• Want to reduce params
§ Package points together
§ How can we do this?
9/20/22 Objects 4
Points as Their Own Type
def distance(p0,p1):
"""Returns distance between points p0 and p1
Param p0: The second point
Precond: p0 is a Point3
Param p1: The second point
Precond: p1 is a Point3"""
…
This lecture will help you
make sense of this spec.
9/20/22 Objects 5
Classes: Custom Types
• Class: Custom type not built into Python
§ Just like with functions: built-in & defined
§ Types not built-in are provided by modules
• Might seem weird: type(1) => <class 'int’>
§ In Python 3 type and class are synonyms
§ We will use the historical term for clarity
introcs provides several classes
9/20/22 Objects 6
Objects: Values for a Class
• Object: A specific value for a class type
§ Remember, a type is a set of values
§ Class could have infinitely many objects
• Example: Class is Point3
§ One object is origin; another x-axis (1,0,0)
§ These objects go in params distance function
• Sometimes refer to objects as instances
§ Because a value is an instance of a class
§ Creating an object is called instantiation
9/20/22 Objects 7
How to Instantiate an Object?
• Other types have literals
§ Example: 1, 'abc’, True
§ No such thing for objects
• Classes are provided by modules
§ Modules typically provide new functions
§ In this case, gives a function to make objects
• Constructor function has same name as class
§ Similar to types and type conversion
§ Example: str is a type, str(1) is a function call
9/20/22 Objects 8
Demonstrating Object Instantiation
>>> from introcs import Point3 # Module with class
>>> p = Point3(0,0,0) # Create point at origin
>>> p # Look at this new point
<class 'introcs.geom.point.Point3'>(0.0,0.0,0.0)
>>> type(p) == Point3 # Check the type
True
>>> q = Point3(1,2,3) # Make new point
>>> q # Look at this new point
<class 'introcs.geom.point.Point3'>(1.0,2.0,3.0)
9/20/22 Objects 9
What Does an Object Look Like?
• Objects can be a bit strange to understand
§ Don’t look as simple as strings or numbers
§ Example: <class 'introcs.Point3'>(0.0,0.0,0.0)
• To understand objects, need to visualize them
§ Use of metaphors to help us think like Python
§ Call frames (assume seen) are an example
• To visualize we rely on the Python Tutor
§ Website linked to from the course page
§ But use only that one! Other tutors are different.
9/20/22 Objects 10
Metaphor: Objects are Folders
>>> import introcs
>>> p = introcs.Point3(0,0,0)
>>> id(p)
id2
p
id2
x 0.0
y 0.0
z 0.0
Point3
Need to import module
that has Point class.
Constructor is function.
Prefix w/ module name.
Unique tab
identifier
9/20/22 Objects 11
Shows the ID of p.
Metaphor: Objects are Folders
id2
p
id2
x 0.0
y 0.0
z 0.0
Point3
• Idea: Data too “big” for p
§ Split into many variables
§ Put the variables in folder
§ They are called attributes
• Folder has an identifier
§ Unique (like a netid)
§ Cannot ever change
§ Has no real meaning;
only identifies folder
Unique tab
identifier
Attribute
9/20/22 Objects 12
Object Variables
• Variable stores object name
§ Reference to the object
§ Reason for folder analogy
• Assignment uses object name
§ Example: q = p
§ Takes name from p
§ Puts the name in q
§ Does not make new folder!
• This is the cause of many
mistakes for beginners
id2
p
id2
x 0.0
y 0.0
z 0.0
Point3
id2
q
9/20/22 Objects 13
Objects and Attributes
• Attributes live inside objects
§ Can access these attributes
§ Can use them in expressions
• Access: <variable>.<attr>
§ Look like module variables
§ Recall: math.pi
• Example
>>> p = introcs.Point3(1,2,3)
>>> a = p.x + p.y
id3
x 1.0
y 2.0
z 3.0
id3
p
Point3
9/20/22 Objects 14
Objects and Attributes
• Attributes live inside objects
§ Can access these attributes
§ Can use them in expressions
• Access: <variable>.<attr>
§ Look like module variables
§ Recall: math.pi
• Example
>>> p = introcs.Point3(1,2,3)
>>> a = p.x + p.y
id3
x 1.0
y 2.0
z 3.0
id3
p
Point3
3.0
a
9/20/22 Objects 15
Objects and Attributes
• Can also assign attributes
§ Reach into folder & change
§ Do without changing p
• <var>.<attr> = <exp>
§ Example: p.x = p.y+p.z
§ See this in visualizer
• This is very powerful
§ Another reason for objects
§ Why need visualization
id3
x 1.0
y 2.0
z 3.0
id3
p
Point3
5.0
x
9/20/22 Objects 16
Exercise: Attribute Assignment
• Recall, q gets name in p
>>> p = introcs.Point3(0,0,0)
>>> q = p
• Execute the assignments:
>>> p.x = 5.6
>>> q.x = 7.4
• What is value of p.x?
9/20/22 Objects 17
id4
p id4
q
A: 5.6
B: 7.4
C: id4
D: I don’t know
id4
x 0.0
y 0.0
z 0.0
Point3
Exercise: Attribute Assignment
• Recall, q gets name in p
>>> p = introcs.Point3(0,0,0)
>>> q = p
• Execute the assignments:
>>> p.x = 5.6
>>> q.x = 7.4
• What is value of p.x?
9/20/22 Objects 18
id4
p id4
q
A: 5.6
B: 7.4
C: id4
D: I don’t know
id4
x 0.0
y 0.0
z 0.0
Point3
5.6
CORRECT
x
Exercise: Attribute Assignment
• Recall, q gets name in p
>>> p = introcs.Point3(0,0,0)
>>> q = p
• Execute the assignments:
>>> p.x = 5.6
>>> q.x = 7.4
• What is value of p.x?
9/20/22 Objects 19
id4
p id4
q
A: 5.6
B: 7.4
C: id4
D: I don’t know
id4
x 0.0
y 0.0
z 0.0
Point3
5.6 7.4
CORRECT
x x
Objects Allow for Mutable Functions
• Mutable function: alters the parameters
§ Often a procedure; no return value
• Until now, this was impossible
§ Function calls COPY values into new variables
§ New variables erased with call frame
§ Original (global?) variable was unaffected
• But object variables are folder names
§ Call frame refers to same folder as original
§ Function may modify the contents of this folder
9/20/22 Objects 20
Example: Mutable Function Call
• Example:
def incr_x(q):
q.x = q.x + 1
>>> p = Point3(0,0,0)
>>> p.x
0.0
>>> incr_x(p)
>>> p.x
1.0
1
incr_x 2
id1
q
Global STUFF
Call Frame
id1
p
id1
0.0
…
Point3
x
2
9/20/22 Objects 21
Example: Mutable Function Call
• Example:
def incr_x(q):
q.x = q.x + 1
>>> p = Point3(0,0,0)
>>> p.x
0.0
>>> incr_x(p)
>>> p.x
1.0
1
incr_x
id1
q
Global STUFF
Call Frame
id1
p
id1
0.0
…
Point3
x
2
1.0
x
9/20/22 Objects 22
Example: Mutable Function Call
• Example:
def incr_x(q):
q.x = q.x + 1
>>> p = Point3(0,0,0)
>>> p.x
0.0
>>> incr_x(p)
>>> p.x
1.0
1
Global STUFF
Call Frame
id1
p
id1
0.0
…
Point3
x
2
1.0
x
ERASE WHOLE FRAME
Change
remains
9/20/22 Objects 23
Methods: Functions Tied to Objects
• Have seen object folders contain variables
§ Syntax: ⟨obj⟩.⟨attribute⟩ (e.g. p.x)
§ These are called attributes
• They can also contain functions
§ Syntax: ⟨obj⟩.⟨method⟩(⟨arguments⟩)
§ Example: p.clamp(-1,1)
§ These are called methods
• Visualizer will not show these inside folders
§ Will see why in November (when cover Classes)
9/20/22 Objects 24
Understanding Method Calls
• Object before the name is an implicit argument
• Example: distance
>>> p = Point3(0,0,0) # First point
>>> q = Point3(1,0,0) # Second point
>>> r = Point3(0,0,1) # Third point
>>> p.distance(r) # Distance between p, r
1.0
>>> q.distance(r) # Distance between q, r
1.4142135623730951
9/20/22 Objects 25
Recall: String Method Calls
• Method calls have the form
string.name(x,y,…)
• The string in front is an additional argument
§ Just one that is not inside of the parentheses
§ Why? Will answer this later in course.
method
name
arguments
argument
Are strings objects?
9/20/22 Objects 26
Surprise: All Values are Objects!
• Including basic values
§ int, float, bool, str
• Example:
>>> x = 1000
>>> id(x) 2.5
x
2.5
id5
id5
x
float
9/20/22 Objects 27
This Explains A Lot of Things
• Basic types act like classes
§ Conversion function is really a constructor
§ Remember constructor, type have same name
• Example:
>>> type(1)
<class 'int'>
>>> int('1')
1
• Design goals of Python 3
§ Wanted everything an object
§ Makes processing cleaner
• But makes learning harder
§ Objects are complex topic
§ Want to delay if possible
9/20/22 Objects 28
But Not Helpful to Think This Way
• Number folders are immutable
§ “Variables” have no names
§ No way to reach in folder
§ No way to change contents
>>> x = 1000
>>> y = 1000
>>> id(x)
4497040368
>>> id(y)
4497040400
>>> y = y+1
>>> id(y)
4497040432
1000
4497040368
4497040368
x
int Makes a brand
new int folder
9/20/22 Objects 29
But Not Helpful to Think This Way
• Number folders are immutable
§ “Variables” have no names
§ No way to reach in folder
§ No way to change contents
• Remember purpose of folder
§ Show how objects can be altered
§ Show how variables “share” data
§ This cannot happen in basic types
• So just ignore the folders
§ (The are just metaphors anyway)
>>> x = 1000
>>> y = 1000
>>> id(x)
4497040368
>>> id(y)
4497040400
>>> y = y+1
>>> id(y)
4497040432
9/20/22 Objects 30
Basic Types vs. Classes
Basic Types
• Built-into Python
• Refer to instances as values
• Instantiate with literals
• Are all immutable
• Can ignore the folders
Classes
• Provided by modules
• Refer to instances as objects
• Instantiate w/ constructors
• Can alter attributes
• Must represent with folders
9/20/22 Objects 31
In doubt? Use the Python Tutor
Where To From Here?
• Right now, just try to understand objects
§ All Python programs use objects
§ The object classes are provided by Python
• OO Programming is about creating classes
§ But we will not get to this until after Prelim 1
• Similar to the separation of functions
§ First learned to call functions (create objects)
§ Then how to define functions (define classes)
9/20/22 Objects 32

More Related Content

PPTX
VTU Python Module 5 , Class and Objects and Debugging
rickyghoshiit
 
PPTX
About Python
Shao-Chuan Wang
 
PDF
Introduction to Python for Plone developers
Jim Roepcke
 
PDF
Introduction to Ruby Programming Language
Nicolò Calcavecchia
 
PPTX
Class and object C++.pptx
SantoshVarshney3
 
PPTX
Classes and objects
Shailendra Veeru
 
PPT
C++ Programming Course
Dennis Chang
 
PPT
Ccourse 140618093931-phpapp02
Getachew Ganfur
 
VTU Python Module 5 , Class and Objects and Debugging
rickyghoshiit
 
About Python
Shao-Chuan Wang
 
Introduction to Python for Plone developers
Jim Roepcke
 
Introduction to Ruby Programming Language
Nicolò Calcavecchia
 
Class and object C++.pptx
SantoshVarshney3
 
Classes and objects
Shailendra Veeru
 
C++ Programming Course
Dennis Chang
 
Ccourse 140618093931-phpapp02
Getachew Ganfur
 

Similar to Python course slides topic objects in python (20)

PPTX
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
PDF
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
horiamommand
 
PDF
Advanced Reflection in Pharo
Pharo
 
PPT
Visual basic intoduction
mohamedsaad24
 
PDF
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JSFestUA
 
PDF
Object Oriented Programming using C++ - Part 4
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
PPT
Object oriented analysis_and_design_v2.0
Ganapathi M
 
PPT
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
PPTX
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
PPTX
4-OOPS.pptx
SatyamMishra237306
 
PPTX
C++ Presen. tation.pptx
mohitsinha7739289047
 
PPT
Oops Concept Java
Kamlesh Singh
 
PDF
Denis Lebedev, Swift
Yandex
 
PPT
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
PPTX
An Introduction : Python
Raghu Kumar
 
PPTX
OOP Presentation.pptx
DurgaPrasadVasantati
 
PPTX
OOP Presentation.pptx
DurgaPrasadVasantati
 
PPT
00-rewfwffwfwfwewfwwfwffeffvyu8ikview.ppt
jotola6956
 
PPT
00 OOP Introduction to Java Lecture Notes.ppt
Ijaduola Ilerioluwa
 
PPTX
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Python 2. classes- cruciql for students objects1.pptx
KiranRaj648995
 
singh singhsinghsinghsinghsinghsinghsinghsinghsingh.pdf
horiamommand
 
Advanced Reflection in Pharo
Pharo
 
Visual basic intoduction
mohamedsaad24
 
JS Fest 2019/Autumn. Daniel Ostrovsky. Falling in love with decorators ES6/Ty...
JSFestUA
 
Object Oriented Programming using C++ - Part 4
University College of Engineering Kakinada, JNTUK - Kakinada, India
 
Object oriented analysis_and_design_v2.0
Ganapathi M
 
02._Object-Oriented_Programming_Concepts.ppt
Yonas D. Ebren
 
Classes, Objects and Method - Object Oriented Programming with Java
Radhika Talaviya
 
4-OOPS.pptx
SatyamMishra237306
 
C++ Presen. tation.pptx
mohitsinha7739289047
 
Oops Concept Java
Kamlesh Singh
 
Denis Lebedev, Swift
Yandex
 
Chap 3 Python Object Oriented Programming - Copy.ppt
muneshwarbisen1
 
An Introduction : Python
Raghu Kumar
 
OOP Presentation.pptx
DurgaPrasadVasantati
 
OOP Presentation.pptx
DurgaPrasadVasantati
 
00-rewfwffwfwfwewfwwfwffeffvyu8ikview.ppt
jotola6956
 
00 OOP Introduction to Java Lecture Notes.ppt
Ijaduola Ilerioluwa
 
UNIT 3 PY.pptx - OOPS CONCEPTS IN PYTHON
drkangurajuphd
 
Ad

More from MuhammadIfitikhar (10)

PPTX
Lecture-00: Azure IoT Pi Day Slides.pptx
MuhammadIfitikhar
 
PPTX
Lecture-6: Azure and Iot hub lecture.pptx
MuhammadIfitikhar
 
PDF
Python Lecture slides topic Algorithm design
MuhammadIfitikhar
 
PDF
Python Slides conditioanls and control flow
MuhammadIfitikhar
 
PDF
Python course lecture slides specifications and testing
MuhammadIfitikhar
 
PDF
Python Lecture Slides topic strings handling
MuhammadIfitikhar
 
PDF
Python Course Lecture Defining Functions
MuhammadIfitikhar
 
PDF
Python Course Functions and Modules Slides
MuhammadIfitikhar
 
PDF
Python Lecture Slides Variables and Assignments
MuhammadIfitikhar
 
PDF
Course Overview Python Basics Course Slides
MuhammadIfitikhar
 
Lecture-00: Azure IoT Pi Day Slides.pptx
MuhammadIfitikhar
 
Lecture-6: Azure and Iot hub lecture.pptx
MuhammadIfitikhar
 
Python Lecture slides topic Algorithm design
MuhammadIfitikhar
 
Python Slides conditioanls and control flow
MuhammadIfitikhar
 
Python course lecture slides specifications and testing
MuhammadIfitikhar
 
Python Lecture Slides topic strings handling
MuhammadIfitikhar
 
Python Course Lecture Defining Functions
MuhammadIfitikhar
 
Python Course Functions and Modules Slides
MuhammadIfitikhar
 
Python Lecture Slides Variables and Assignments
MuhammadIfitikhar
 
Course Overview Python Basics Course Slides
MuhammadIfitikhar
 
Ad

Recently uploaded (20)

PPTX
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PDF
Protecting the Digital World Cyber Securit
dnthakkar16
 
PDF
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
PPTX
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PDF
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
PDF
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PDF
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
PDF
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
Exploring AI Agents in Process Industries
amoreira6
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
The-Dawn-of-AI-Reshaping-Our-World.pptxx
parthbhanushali307
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Protecting the Digital World Cyber Securit
dnthakkar16
 
Key Features to Look for in Arizona App Development Services
Net-Craft.com
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Contractor Management Platform and Software Solution for Compliance
SHEQ Network Limited
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
Microsoft Teams Essentials; The pricing and the versions_PDF.pdf
Q-Advise
 
ShowUs: Pharo Stream Deck (ESUG 2025, Gdansk)
ESUG
 
Presentation about variables and constant.pptx
kr2589474
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
lesson-2-rules-of-netiquette.pdf.bshhsjdj
jasmenrojas249
 
Wondershare Filmora 14.5.20.12999 Crack Full New Version 2025
gsgssg2211
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
Exploring AI Agents in Process Industries
amoreira6
 
Explanation about Structures in C language.pptx
Veeral Rathod
 

Python course slides topic objects in python

  • 2. Announcements for Today Assignment 1 • We have finished grading • Resubmit until correct § Read feedback in CMS § Reupload/request regrade • If you were very wrong… § You received an e-mail § More 1-on-1s this week • Finish Survey 1 Assignment 2 • Posted last Friday § Written assignment § Do while revising A1 § Relatively short (2-3 hrs) • Due Thursday § Submit as a PDF § Scan or phone picture § US Letter format! 9/20/22 Objects 2
  • 3. The Basic Python Types • Type int: § Values: integers § Ops: +, –, *, //, %, ** • Type float: § Values: real numbers § Ops: +, –, *, /, ** • Type bool: § Values: True and False § Ops: not, and, or • Type str: § Values: string literals • Double quotes: "abc" • Single quotes: 'abc' § Ops: + (concatenation) 9/20/22 Objects 3 Are the the only types that exist?
  • 4. Example: Points in 3D Space def distance(x0,y0,z0,x1,y1,z1): """Returns distance between points (x0,y0,y1) and (x1,y1,z1) Param x0: x-coord of 1st point Precond: x0 is a float Param y0: y-coord of 1st point Precond: y0 is a float Param z0: z-coord of 1st point Precond: z0 is a float …. """ • This is very unwieldy § Specification is too long § Calls needs many params § Typo bugs are very likely • Want to reduce params § Package points together § How can we do this? 9/20/22 Objects 4
  • 5. Points as Their Own Type def distance(p0,p1): """Returns distance between points p0 and p1 Param p0: The second point Precond: p0 is a Point3 Param p1: The second point Precond: p1 is a Point3""" … This lecture will help you make sense of this spec. 9/20/22 Objects 5
  • 6. Classes: Custom Types • Class: Custom type not built into Python § Just like with functions: built-in & defined § Types not built-in are provided by modules • Might seem weird: type(1) => <class 'int’> § In Python 3 type and class are synonyms § We will use the historical term for clarity introcs provides several classes 9/20/22 Objects 6
  • 7. Objects: Values for a Class • Object: A specific value for a class type § Remember, a type is a set of values § Class could have infinitely many objects • Example: Class is Point3 § One object is origin; another x-axis (1,0,0) § These objects go in params distance function • Sometimes refer to objects as instances § Because a value is an instance of a class § Creating an object is called instantiation 9/20/22 Objects 7
  • 8. How to Instantiate an Object? • Other types have literals § Example: 1, 'abc’, True § No such thing for objects • Classes are provided by modules § Modules typically provide new functions § In this case, gives a function to make objects • Constructor function has same name as class § Similar to types and type conversion § Example: str is a type, str(1) is a function call 9/20/22 Objects 8
  • 9. Demonstrating Object Instantiation >>> from introcs import Point3 # Module with class >>> p = Point3(0,0,0) # Create point at origin >>> p # Look at this new point <class 'introcs.geom.point.Point3'>(0.0,0.0,0.0) >>> type(p) == Point3 # Check the type True >>> q = Point3(1,2,3) # Make new point >>> q # Look at this new point <class 'introcs.geom.point.Point3'>(1.0,2.0,3.0) 9/20/22 Objects 9
  • 10. What Does an Object Look Like? • Objects can be a bit strange to understand § Don’t look as simple as strings or numbers § Example: <class 'introcs.Point3'>(0.0,0.0,0.0) • To understand objects, need to visualize them § Use of metaphors to help us think like Python § Call frames (assume seen) are an example • To visualize we rely on the Python Tutor § Website linked to from the course page § But use only that one! Other tutors are different. 9/20/22 Objects 10
  • 11. Metaphor: Objects are Folders >>> import introcs >>> p = introcs.Point3(0,0,0) >>> id(p) id2 p id2 x 0.0 y 0.0 z 0.0 Point3 Need to import module that has Point class. Constructor is function. Prefix w/ module name. Unique tab identifier 9/20/22 Objects 11 Shows the ID of p.
  • 12. Metaphor: Objects are Folders id2 p id2 x 0.0 y 0.0 z 0.0 Point3 • Idea: Data too “big” for p § Split into many variables § Put the variables in folder § They are called attributes • Folder has an identifier § Unique (like a netid) § Cannot ever change § Has no real meaning; only identifies folder Unique tab identifier Attribute 9/20/22 Objects 12
  • 13. Object Variables • Variable stores object name § Reference to the object § Reason for folder analogy • Assignment uses object name § Example: q = p § Takes name from p § Puts the name in q § Does not make new folder! • This is the cause of many mistakes for beginners id2 p id2 x 0.0 y 0.0 z 0.0 Point3 id2 q 9/20/22 Objects 13
  • 14. Objects and Attributes • Attributes live inside objects § Can access these attributes § Can use them in expressions • Access: <variable>.<attr> § Look like module variables § Recall: math.pi • Example >>> p = introcs.Point3(1,2,3) >>> a = p.x + p.y id3 x 1.0 y 2.0 z 3.0 id3 p Point3 9/20/22 Objects 14
  • 15. Objects and Attributes • Attributes live inside objects § Can access these attributes § Can use them in expressions • Access: <variable>.<attr> § Look like module variables § Recall: math.pi • Example >>> p = introcs.Point3(1,2,3) >>> a = p.x + p.y id3 x 1.0 y 2.0 z 3.0 id3 p Point3 3.0 a 9/20/22 Objects 15
  • 16. Objects and Attributes • Can also assign attributes § Reach into folder & change § Do without changing p • <var>.<attr> = <exp> § Example: p.x = p.y+p.z § See this in visualizer • This is very powerful § Another reason for objects § Why need visualization id3 x 1.0 y 2.0 z 3.0 id3 p Point3 5.0 x 9/20/22 Objects 16
  • 17. Exercise: Attribute Assignment • Recall, q gets name in p >>> p = introcs.Point3(0,0,0) >>> q = p • Execute the assignments: >>> p.x = 5.6 >>> q.x = 7.4 • What is value of p.x? 9/20/22 Objects 17 id4 p id4 q A: 5.6 B: 7.4 C: id4 D: I don’t know id4 x 0.0 y 0.0 z 0.0 Point3
  • 18. Exercise: Attribute Assignment • Recall, q gets name in p >>> p = introcs.Point3(0,0,0) >>> q = p • Execute the assignments: >>> p.x = 5.6 >>> q.x = 7.4 • What is value of p.x? 9/20/22 Objects 18 id4 p id4 q A: 5.6 B: 7.4 C: id4 D: I don’t know id4 x 0.0 y 0.0 z 0.0 Point3 5.6 CORRECT x
  • 19. Exercise: Attribute Assignment • Recall, q gets name in p >>> p = introcs.Point3(0,0,0) >>> q = p • Execute the assignments: >>> p.x = 5.6 >>> q.x = 7.4 • What is value of p.x? 9/20/22 Objects 19 id4 p id4 q A: 5.6 B: 7.4 C: id4 D: I don’t know id4 x 0.0 y 0.0 z 0.0 Point3 5.6 7.4 CORRECT x x
  • 20. Objects Allow for Mutable Functions • Mutable function: alters the parameters § Often a procedure; no return value • Until now, this was impossible § Function calls COPY values into new variables § New variables erased with call frame § Original (global?) variable was unaffected • But object variables are folder names § Call frame refers to same folder as original § Function may modify the contents of this folder 9/20/22 Objects 20
  • 21. Example: Mutable Function Call • Example: def incr_x(q): q.x = q.x + 1 >>> p = Point3(0,0,0) >>> p.x 0.0 >>> incr_x(p) >>> p.x 1.0 1 incr_x 2 id1 q Global STUFF Call Frame id1 p id1 0.0 … Point3 x 2 9/20/22 Objects 21
  • 22. Example: Mutable Function Call • Example: def incr_x(q): q.x = q.x + 1 >>> p = Point3(0,0,0) >>> p.x 0.0 >>> incr_x(p) >>> p.x 1.0 1 incr_x id1 q Global STUFF Call Frame id1 p id1 0.0 … Point3 x 2 1.0 x 9/20/22 Objects 22
  • 23. Example: Mutable Function Call • Example: def incr_x(q): q.x = q.x + 1 >>> p = Point3(0,0,0) >>> p.x 0.0 >>> incr_x(p) >>> p.x 1.0 1 Global STUFF Call Frame id1 p id1 0.0 … Point3 x 2 1.0 x ERASE WHOLE FRAME Change remains 9/20/22 Objects 23
  • 24. Methods: Functions Tied to Objects • Have seen object folders contain variables § Syntax: ⟨obj⟩.⟨attribute⟩ (e.g. p.x) § These are called attributes • They can also contain functions § Syntax: ⟨obj⟩.⟨method⟩(⟨arguments⟩) § Example: p.clamp(-1,1) § These are called methods • Visualizer will not show these inside folders § Will see why in November (when cover Classes) 9/20/22 Objects 24
  • 25. Understanding Method Calls • Object before the name is an implicit argument • Example: distance >>> p = Point3(0,0,0) # First point >>> q = Point3(1,0,0) # Second point >>> r = Point3(0,0,1) # Third point >>> p.distance(r) # Distance between p, r 1.0 >>> q.distance(r) # Distance between q, r 1.4142135623730951 9/20/22 Objects 25
  • 26. Recall: String Method Calls • Method calls have the form string.name(x,y,…) • The string in front is an additional argument § Just one that is not inside of the parentheses § Why? Will answer this later in course. method name arguments argument Are strings objects? 9/20/22 Objects 26
  • 27. Surprise: All Values are Objects! • Including basic values § int, float, bool, str • Example: >>> x = 1000 >>> id(x) 2.5 x 2.5 id5 id5 x float 9/20/22 Objects 27
  • 28. This Explains A Lot of Things • Basic types act like classes § Conversion function is really a constructor § Remember constructor, type have same name • Example: >>> type(1) <class 'int'> >>> int('1') 1 • Design goals of Python 3 § Wanted everything an object § Makes processing cleaner • But makes learning harder § Objects are complex topic § Want to delay if possible 9/20/22 Objects 28
  • 29. But Not Helpful to Think This Way • Number folders are immutable § “Variables” have no names § No way to reach in folder § No way to change contents >>> x = 1000 >>> y = 1000 >>> id(x) 4497040368 >>> id(y) 4497040400 >>> y = y+1 >>> id(y) 4497040432 1000 4497040368 4497040368 x int Makes a brand new int folder 9/20/22 Objects 29
  • 30. But Not Helpful to Think This Way • Number folders are immutable § “Variables” have no names § No way to reach in folder § No way to change contents • Remember purpose of folder § Show how objects can be altered § Show how variables “share” data § This cannot happen in basic types • So just ignore the folders § (The are just metaphors anyway) >>> x = 1000 >>> y = 1000 >>> id(x) 4497040368 >>> id(y) 4497040400 >>> y = y+1 >>> id(y) 4497040432 9/20/22 Objects 30
  • 31. Basic Types vs. Classes Basic Types • Built-into Python • Refer to instances as values • Instantiate with literals • Are all immutable • Can ignore the folders Classes • Provided by modules • Refer to instances as objects • Instantiate w/ constructors • Can alter attributes • Must represent with folders 9/20/22 Objects 31 In doubt? Use the Python Tutor
  • 32. Where To From Here? • Right now, just try to understand objects § All Python programs use objects § The object classes are provided by Python • OO Programming is about creating classes § But we will not get to this until after Prelim 1 • Similar to the separation of functions § First learned to call functions (create objects) § Then how to define functions (define classes) 9/20/22 Objects 32