KEMBAR78
Python course slides topic objects in python | PDF
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

Python course slides topic objects in python

  • 1.
  • 2.
    Announcements for Today Assignment1 • 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 PythonTypes • 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 in3D 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 TheirOwn 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 fora 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 Instantiatean 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 anObject 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 areFolders >>> 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 areFolders 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 • Variablestores 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 forMutable 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 FunctionCall • 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 FunctionCall • 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 FunctionCall • 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 Tiedto 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 MethodCalls • 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 Valuesare 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 ALot 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 Helpfulto 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 Helpfulto 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 FromHere? • 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