Lecture 17 Classes
Announcements for This Lecture Assignments Lab this Week • A4 Thursday at midnight • More prelim exercises § Hopefully you are on Task 4 § This time for-loops § Minor extension for reasons § Plus a simple class • Will post A5 on Wednesday Exams § Written assignment like A2 § Needs material from Tues • Last week for regrades • Will post A6 on Friday § Limit them to valid issues § Not due until November 14 • Getting closer to prelim 2 § Want to avoid exam crunch 10/23/18 Classes 2
Recall: Objects as Data in Folders • An object is like a manila folder Unique tab identifier • It contains other variables § Variables are called attributes id2 § Can change values of an attribute (with assignment statements) 2.0 x • It has a “tab” that identifies it 3.0 y § Unique number assigned by Python § Fixed for lifetime of the object 5.0 z 10/23/18 Classes 3
Recall: Classes are Types for Objects • Values must have a type • Classes are how we add new types to Python § An object is a value § Object type is a class id2 Types Point3 • int Classes 2.0 x • float class name • Point3 • bool • RGB 3.0 y • str • Turtle • Window 5.0 z 10/23/18 Classes 4
Recall: Classes are Types for Objects • Values must have a type • Classes are how we add new types to Python § An object is a value § Object type is a class id2 Types But in Python3, type and class Point3 • int Classes are now both synonyms 2.0 x • float class name • Point3 • bool • RGB 3.0 y • str • Turtle • Window 5.0 z 10/23/18 Classes 5
Classes Have Folders Too Object Folders Class Folders • Separate for each instance • Data common to all instances id2 Point3 Point3 id3 x 2.0 Point3 ???? y 3.0 x 5.0 z 5.0 y 7.2 z -0.5 10/23/18 Classes 6
Name Resolution for Objects id3 id4 • ⟨ object ⟩ . ⟨ name ⟩ means p q id3 id4 § Go the folder for object Point3 Point3 § Find attribute/method name x 5.0 x 7.4 § If missing, check class folder y 2.0 y 0.0 § If not in either, raise error z 3.0 z 0.0 • What is in the class folder? Point3 § Data common to all objects § First must understand the ???? class definition 10/23/18 Classes 7
Goes inside a The Class Definition module, just like a function definition. class < class-name > (object): """Class specification""" < function definitions > < assignment statements > < any other statements also allowed> Example class Example(object): """The simplest possible class.""" pass 10/23/18 Classes 8
Goes inside a The Class Definition module, just like a function keyword class definition. Beginning of a class < class-name > (object): class definition Do not forget the colon! Specification """Class specification""" more on this later (similar to one for a function) < function definitions > to define …but not often used < assignment statements > methods < any other statements also allowed> to define Example attributes class Example(object): Python creates """The simplest possible class.""" after reading the pass class definition 10/23/18 Classes 9
Recall: Constructors • Function to create new instances id2 e id2 § Function name == class name Example § Created for you automatically • Calling the constructor: § Makes a new object folder Will come § Initializes attributes Example back to this § Returns the id of the folder • By default, takes no arguments § e = Example() 10/23/18 Classes 10
Instances and Attributes • Assignments add object attributes id2 e § <object>.<att> = <expression> id2 § Example : e.b = 42 Example • Assignments can add class attributes 42 b § <class>.<att> = <expression> § Example : Example.a = 29 • Objects can access class attributes Example § Example : print e.a § But assigning it creates object attribute 29 a § Example : e.a = 10 • Rule : check object first, then class 10/23/18 Classes 11
Instances and Attributes • Assignments add object attributes id2 e § <object>.<att> = <expression> id2 § Example : e.b = 42 Not how Example usually done • Assignments can add class attributes 42 b § <class>.<att> = <expression> § Example : Example.a = 29 • Objects can access class attributes Example § Example : print e.a § But assigning it creates object attribute 29 a § Example : e.a = 10 • Rule : check object first, then class 10/23/18 Classes 12
Instances and Attributes • Assignments add object attributes id2 e § <object>.<att> = <expression> id2 § Example : e.b = 42 Example • Assignments can add class attributes 42 b § <class>.<att> = <expression> 10 a § Example : Example.a = 29 • Objects can access class attributes Example § Example : print e.a § But assigning it creates object attribute 29 a § Example : e.a = 10 • Rule : check object first, then class 10/23/18 Classes 13
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 specification 10/23/18 Classes 14
The Class Specification class Worker(object): """An instance is a worker in an organization. Instance has basic worker info, but no salary information. ATTRIBUTES: lname: Worker’s last name. [str] ssn: Social security no. [int in 0..999999999] boss: Worker's boss. [Worker, or None if no boss] 10/23/18 Classes 15
The Class Specification Short class Worker(object): summary """An instance is a worker in an organization. More detail Instance has basic worker info, but no salary information. Attribute list Description ATTRIBUTES: Invariant lname: Worker’s last name. [str] ssn: Social security no. [int in 0..999999999] Attribute Name boss: Worker's boss. [Worker, or None if no boss] 10/23/18 Classes 16
Recall: Objects can have Methods id3 id4 • Method : function tied to object p q § Function call: id3 id4 <function-name>(<arguments>) Point3 Point3 § Method call: x 5.0 x 7.4 <object-variable>.<function-call> y 2.0 y 0.0 • Example : p.distance(q) z 3.0 z 0.0 § Both p and q act as arguments § Very much like distanceTo(p, q) Point3 • For most Python objects __init__(x, y, z) § Attributes are in object folder distanceTo(other) abs() § Methods are in class folder 10/23/18 Classes 17
Method Definitions class Point3(object): • Looks like a function def """Instances are points in 3d space § But indented inside class x: x coord [float] § The first parameter y: y coord [float] is always called self z: z coord [float] """ • In a method call: def distance(self,q): """Returns: dist from self to q § Parentheses have one less Precondition: q a Point3""" argument than parameters assert type(q) == Point3 § The object in front is sqrdst = ((self.x-q.x)**2 + passed to parameter self (self.y-q.y)**2 + • Example : a.distance(b) (self.z-q.z)**2) return math.sqrt(sqrdst) q self 10/23/18 Classes 18
Methods Calls • Example : a.distance(b) class Point3(object): """Instances are points in 3d space a id2 b id3 x: x coord [float] y: y coord [float] id2 id3 z: z coord [float] """ Point3 Point3 x 1.0 x 0.0 def distance(self,q): y 2.0 y 3.0 """Returns: dist from self to q z 3.0 z -1.0 Precondition: q a Point3""" assert type(q) == Point3 sqrdst = ((self.x-q.x)**2 + (self.y-q.y)**2 + (self.z-q.z)**2) return math.sqrt(sqrdst) 10/23/18 Classes 19
Methods Calls • Example : a.distance(b) class Point3(object): """Instances are points in 3d space a id2 b id3 x: x coord [float] y: y coord [float] id2 id3 z: z coord [float] """ Point3 Point3 x 1.0 x 0.0 def distance(self,q): y 2.0 y 3.0 """Returns: dist from self to q z 3.0 z -1.0 Precondition: q a Point3""" assert type(q) == Point3 distance 1 sqrdst = ((self.x-q.x)**2 + (self.y-q.y)**2 + self id2 (self.z-q.z)**2) q id3 return math.sqrt(sqrdst) 10/23/18 Classes 20
Initializing the Attributes of an Object (Folder) • C reating a new Worker is a multi-step process: § w = Worker() Instance is empty § w.lname = 'White' § … • Want to use something like w = Worker('White', 1234, None) § Create a new Worker and assign attributes § lname to 'White' , ssn to 1234, and boss to None • Need a custom constructor 10/23/18 Classes 21
Special Method: __init__ w = Worker('White', 1234, None) Called by the constructor def __init__(self, n, s, b): """Initializer: creates a Worker id8 Worker Has last name n, SSN s, and boss b lname 'White' Precondition: n a string, s an int in ssn 1234 range 0..999999999, and b either a Worker or None. boss None self.lname = n self.ssn = s self.boss = b 10/23/18 Classes 22
Recommend
More recommend