Classes - cs.cornell.edu

35
Classes Lecture 17

Transcript of Classes - cs.cornell.edu

Page 1: Classes - cs.cornell.edu

Classes

Lecture 17

Page 2: Classes - cs.cornell.edu

Announcements for This Lecture

10/26/21 2Classes

• A4 Thursday at midnight§ Hopefully you are on Task 4§ That and task 5 are hardest

• Will post A5 on Thursday§ Written assignment like A2§ Needs material from Tues

• Will post A6 on Nov 2.§ Not due until November 16§ But is relevant for prelim 2!

Optional VideosAssignments

• Videos 20.1-20.8 today• Videos 20.9-20.10 next time• Also Lesson 21 next time

• Last week for regrades§ Limit them to valid issues

• We will do them eventually

Exams

Page 3: Classes - cs.cornell.edu

Recall: Objects as Data in Folders

• An object is like a manila folder• It contains other variables

§ Variables are called attributes§ Can change values of an attribute

(with assignment statements)• It has a “tab” that identifies it

§ Unique number assigned by Python§ Fixed for lifetime of the object

10/26/21 3

id2

x 2.0

y 3.0

z 5.0

Unique tabidentifier

Classes

Page 4: Classes - cs.cornell.edu

Recall: Classes are Types for Objects

• Values must have a type§ An object is a value§ A class is its type

• Classes are how we add new types to Python

10/26/21 4

id2

x 2.0

y 3.0

z 5.0

Point3

class nameClasses• Point3• RGB• Turtle• Window

Types

• int• float• bool• str

Classes

Page 5: Classes - cs.cornell.edu

Recall: Classes are Types for Objects

• Values must have a type§ An object is a value§ A class is its type

• Classes are how we add new types to Python

10/26/21 5

id2

x 2.0

y 3.0

z 5.0

Point3

class nameClasses• Point3• RGB• Turtle• Window

Types

• int• float• bool• str

Classes

In Python3, type and classare now both synonyms

Page 6: Classes - cs.cornell.edu

Classes Have Folders Too

Object Folders

• Separate for each instance

Class Folders

• Data common to all instances

10/26/21 Classes 6

id2

x 2.0

y 3.0

z 5.0

Point3id3

x 5.0

y 7.2

z -0.5

Point3

Point3

????

Page 7: Classes - cs.cornell.edu

The Class Definition

class <class-name>(object):

"""Class specification"""

<function definitions>

<assignment statements>

<any other statements also allowed>

Goes inside a module, just

like a function definition.

class Example(object):"""The simplest possible class."""pass

10/26/21 Classes 7

Example

Page 8: Classes - cs.cornell.edu

The Class Definition

class <class-name>(object):

"""Class specification"""

<function definitions>

<assignment statements>

<any other statements also allowed>

Goes inside a module, just

like a function definition.keyword class

Beginning of a class definition

more on this laterSpecification(similar to one for a function)

Do not forget the colon!

to define methods

…but not often used

to define attributes

class Example(object):"""The simplest possible class."""pass

10/26/21 Classes 8

Example

Python creates after reading the class definition

Page 9: Classes - cs.cornell.edu

Recall: Constructors

• Function to create new instances§ Function name == class name

§ Created for you automatically

• Calling the constructor:§ Makes a new object folder

§ Initializes attributes

§ Returns the id of the folder

• By default, takes no arguments§ e = Example()

10/26/21 Classes

id2id2e

Example

Example

Will come back to this

9

Page 10: Classes - cs.cornell.edu

Instances and Attributes• Assignments add object attributes

§ <object>.<att> = <expression>§ Example: e.b = 42

• Assignments can add class attributes§ <class>.<att> = <expression>§ Example: Example.a = 29

• Objects can access class attributes§ Example: print(e.a)§ But assigning it creates object attribute§ Example: e.a = 10

• Rule: check object first, then class10/26/21 Classes

id2id2e

Example

Example

42b

29a

10

Page 11: Classes - cs.cornell.edu

Instances and Attributes• Assignments add object attributes

§ <object>.<att> = <expression>§ Example: e.b = 42

• Assignments can add class attributes§ <class>.<att> = <expression>§ Example: Example.a = 29

• Objects can access class attributes§ Example: print(e.a)§ But assigning it creates object attribute§ Example: e.a = 10

• Rule: check object first, then class10/26/21 Classes

id2id2e

Example

Example

42b

29a

Not how usually done

11

Page 12: Classes - cs.cornell.edu

Instances and Attributes• Assignments add object attributes

§ <object>.<att> = <expression>§ Example: e.b = 42

• Assignments can add class attributes§ <class>.<att> = <expression>§ Example: Example.a = 29

• Objects can access class attributes§ Example: print(e.a)§ But assigning it creates object attribute§ Example: e.a = 10

• Rule: check object first, then class10/26/21 Classes

id2id2e

Example

Example

42b

29a

10a

12

Page 13: Classes - cs.cornell.edu

Invariants

• Properties of an attribute that must be true• Works like a precondition:

§ If invariant satisfied, object works properly§ If not satisfied, object is “corrupted”

• Examples:§ Point3 class: all attributes must be floats§ RGB class: all attributes must be ints in 0..255

• Purpose of the class specification10/26/21 Classes 13

Page 14: Classes - cs.cornell.edu

The Class Specification

class Worker(object):"""A class representing a worker in a certain organization

Instance has basic worker info, but no salary information.

Attribute lname: The worker last nameInvariant: lname is a string

Attribute ssn: The Social Security numberInvariant: ssn is an int in the range 0..999999999

Attribute boss: The worker's bossInvariant: boss is an instace of Worker, or None if no boss"""

10/26/21 Classes 14

Page 15: Classes - cs.cornell.edu

The Class Specification

class Worker(object):"""A class representing a worker in a certain organization

Instance has basic worker info, but no salary information.

Attribute lname: The worker last nameInvariant: lname is a string

Attribute ssn: The Social Security numberInvariant: ssn is an int in the range 0..999999999

Attribute boss: The worker's bossInvariant: boss is an instace of Worker, or None if no boss"""

10/26/21 Classes 15

Description

Invariant

Shortsummary

Moredetail

Page 16: Classes - cs.cornell.edu

The Class Specification

class Worker(object):"""A class representing a worker in a certain organization

Instance has basic worker info, but no salary information.

Attribute lname: The worker last nameInvariant: lname is a string

Attribute ssn: The Social Security numberInvariant: ssn is an int in the range 0..999999999

Attribute boss: The worker's bossInvariant: boss is an instace of Worker, or None if no boss"""

10/26/21 Classes 16

Warning: New format since 2019.Old exams will be very different.

Page 17: Classes - cs.cornell.edu

Recall: Objects can have Methods

• 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, r1.0>>> q.distance(r) # Distance between q, r1.4142135623730951

10/26/21 Classes 17

Page 18: Classes - cs.cornell.edu

Method Definitions

• Looks like a function def§ Indented inside class§ First param is always self§ But otherwise the same

• In a method call:§ One less argument in ()§ Obj in front goes to self

• Example: a.distance(b)

1. class Point3(object):2. """Class for points in 3d space3. Invariant: x is a float4. Invariant y is a float5. Invariant z is a float """6. def distance(self,q):7. """Returns dist from self to q8. Precondition: q a Point3"""9. assert type(q) == Point310. sqrdst = ((self.x-q.x)**2 +11. (self.y-q.y)**2 +12. (self.z-q.z)**2)13. return math.sqrt(sqrdst)

10/26/21 Classes 18

self q

Page 19: Classes - cs.cornell.edu

Methods Calls

• Example: a.distance(b) 1. class Point3(object):2. """Class for points in 3d space3. Invariant: x is a float4. Invariant y is a float5. Invariant z is a float """6. def distance(self,q):7. """Returns dist from self to q8. Precondition: q a Point3"""9. assert type(q) == Point310. sqrdst = ((self.x-q.x)**2 +11. (self.y-q.y)**2 +12. (self.z-q.z)**2)13. return math.sqrt(sqrdst)

10/26/21 19

id2Point3

id3b

x 1.0

y

z

2.0

3.0

id3Point3

x 0.0

y

z

3.0

-1.0

id2a

Classes

Page 20: Classes - cs.cornell.edu

Methods Calls

• Example: a.distance(b) 1. class Point3(object):2. """Class for points in 3d space3. Invariant: x is a float4. Invariant y is a float5. Invariant z is a float """6. def distance(self,q):7. """Returns dist from self to q8. Precondition: q a Point3"""9. assert type(q) == Point310. sqrdst = ((self.x-q.x)**2 +11. (self.y-q.y)**2 +12. (self.z-q.z)**2)13. return math.sqrt(sqrdst)

10/26/21 20

id2Point3

id3b

x 1.0

y

z

2.0

3.0

id3Point3

x 0.0

y

z

3.0

-1.0

id2a

Point3.distance 9

id3q

id2self

Classes

Page 21: Classes - cs.cornell.edu

Methods and Folders

• Function definitions…§ make a folder in heap§ assign name as variable§ variable in global space

• Methods are similar...§ Variable in class folder§ But otherwise the same

• Rule of this course§ Put header in class folder§ Nothing else!

1. class Point3(object):2. """Class for points in 3d space3. Invariant: x is a float4. Invariant y is a float5. Invariant z is a float """6. def distance(self,q):

….

10/26/21 Classes 21

distance(self,q)

Point3

Page 22: Classes - cs.cornell.edu

Methods and Folders

10/26/21 Classes 22

Just this

Page 23: Classes - cs.cornell.edu

Initializing the Attributes of an Object (Folder)

• Creating a new Worker is a multi-step process:§ w = Worker()§ w.lname = 'White'§ …

• Want to use something likew = Worker('White', 1234, None)

§ Create a new Worker and assign attributes§ lname to 'White', ssn to 1234, and boss to None

• Need a custom constructor10/26/21 23

Instance is empty

Classes

Page 24: Classes - cs.cornell.edu

Special Method: __init__

def __init__(self, n, s, b):"""Initializes a Worker object

Has last name n, SSN s, and boss b

Precondition: n a string, s an int in range 0..999999999, b either a Worker or None. """self.lname = nself.ssn = sself.boss = b

10/26/21 Classes 24

w = Worker('White', 1234, None)

id8

lname 'White'

ssn

boss

1234

None

Worker

Called by the constructor

Page 25: Classes - cs.cornell.edu

Special Method: __init__

def __init__(self, n, s, b):"""Initializes a Worker object

Has last name n, SSN s, and boss b

Precondition: n a string, s an int in range 0..999999999, b either a Worker or None. """self.lname = nself.ssn = sself.boss = b

10/26/21 Classes 25

w = Worker('White', 1234, None)

id8

lname 'White'

ssn

boss

1234

None

Worker

Called by the constructordon’t forget selftwo underscores

use self to assign attributes

Page 26: Classes - cs.cornell.edu

Evaluating a Constructor Expression

Worker('White', 1234, None)

1. Creates a new object (folder) of the class Worker§ Instance is initially empty

2. Puts the folder into heap space3. Executes the method __init__

§ Passes folder name to self§ Passes other arguments in order§ Executes the (assignment)

commands in initializer body4. Returns the object (folder) name

10/26/21 Classes 26

id8

lname 'White'

ssn

boss

1234

None

Worker

Page 27: Classes - cs.cornell.edu

Aside: The Value None

• The boss field is a problem.§ boss refers to a Worker object§ Some workers have no boss§ Or maybe not assigned yet

(the buck stops there)• Solution: use value None

§ None: Lack of (folder) name§ Will reassign the field later!

• Be careful with None values§ var3.x gives error!§ There is no name in var3§ Which Point3 to use?

id5Point3

id5var1

id6var2

Nonevar3

x 2.2

y

z

5.4

6.7

id6Point3

x 3.5

y

z

-2.0

0.010/26/21 Classes 27

Page 28: Classes - cs.cornell.edu

A Class Definition

class Example(object):

def __init__(self,x):self.x = x

def foo(self,y):x = self.bar(y+1)return x

def bar(self,y):self.x = y-1return self.x

>>> a = Example(3)

10/26/21 Classes 28

1312

1415161718192021

What does the heaplook like now?

Ignoring the class folderwhat does the call stack and the heap look like?

Page 29: Classes - cs.cornell.edu

B:

C: D:

A:

Which One is Closest to Your Answer?

10/26/21 Classes 29

id1Example

3x

id1Example

id1Example

Ex.__init__ 13

id1self 3x

Ex.__init__ 13

id1self 3x

Page 30: Classes - cs.cornell.edu

A Class Definition

class Example(object):

def __init__(self,x):self.x = x

def foo(self,y):x = self.bar(y+1)return x

def bar(self,y):self.x = y-1return self.x

>>> a = Example(3)

10/26/21 Classes 30

1312

1415161718192021

What is the next step?

D:id1

Example

Page 31: Classes - cs.cornell.edu

B:

C: D:

A:

Which One is Closest to Your Answer?

10/26/21 Classes 31

id1Example

3x

id1Example

3x

id1Example

id1Example

Ex.__init__ 13

id1self 3x

Ex.__init__ 13

id1self 3x

Ex.__init__ 13

3x

Ex.__init__ 13

3x

Page 32: Classes - cs.cornell.edu

A Class Definition

class Example(object):

def __init__(self,x):self.x = x

def foo(self,y):x = self.bar(y+1)return x

def bar(self,y):self.x = y-1return self.x

>>> a = Example(3)

10/26/21 Classes 32

1312

1415161718192021

What is the next step?

B:id1

Example

Ex.__init__ 13

id1self 3x

Page 33: Classes - cs.cornell.edu

Making Arguments Optional

• We can assign default values to __init__ arguments§ Write as assignments to

parameters in definition§ Parameters with default

values are optional• Examples:

§ p = Point3() # (0,0,0)§ p = Point3(1,2,3) # (1,2,3)§ p = Point3(1,2) # (1,2,0)§ p = Point3(y=3) # (0,3,0)§ p = Point3(1,z=2) # (1,0,2)

1. class Point3(object):2. """Class for points in 3d space3. Invariant: x is a float4. Invariant y is a float5. Invariant z is a float """6.7. def __init__(self,x=0,y=0,z=0):8. """Initializes a new Point39. Precond: x,y,z are numbers"""10. self.x = x11. self.y = y12. self.z = z13. …

10/26/21 33Classes

Page 34: Classes - cs.cornell.edu

Making Arguments Optional

• We can assign default values to __init__ arguments§ Write as assignments to

parameters in definition§ Parameters with default

values are optional• Examples:

§ p = Point3() # (0,0,0)§ p = Point3(1,2,3) # (1,2,3)§ p = Point3(1,2) # (1,2,0)§ p = Point3(y=3) # (0,3,0)§ p = Point3(1,z=2) # (1,0,2)

1. class Point3(object):2. """Class for points in 3d space3. Invariant: x is a float4. Invariant y is a float5. Invariant z is a float """6.7. def __init__(self,x=0,y=0,z=0):8. """Initializes a new Point39. Precond: x,y,z are numbers"""10. self.x = x11. self.y = y12. self.z = z13. …

10/26/21 34Classes

Assigns in order

Use parameter name when out of order

Can mix two approaches

Page 35: Classes - cs.cornell.edu

Making Arguments Optional

• We can assign default values to __init__ arguments§ Write as assignments to

parameters in definition§ Parameters with default

values are optional• Examples:

§ p = Point3() # (0,0,0)§ p = Point3(1,2,3) # (1,2,3)§ p = Point3(1,2) # (1,2,0)§ p = Point3(y=3) # (0,3,0)§ p = Point3(1,z=2) # (1,0,2)

1. class Point3(object):2. """Class for points in 3d space3. Invariant: x is a float4. Invariant y is a float5. Invariant z is a float """6.7. def __init__(self,x=0,y=0,z=0):8. """Initializes a new Point39. Precond: x,y,z are numbers"""10. self.x = x11. self.y = y12. self.z = z13. …

10/26/21 35Classes

Assigns in order

Use parameter name when out of order

Can mix two approaches

Not limited to methods.

Can do with any function.