lecture 17 classes
play

Lecture 17: Classes (Chapter 15) CS 1110 Introduction to - PowerPoint PPT Presentation

http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 17: Classes (Chapter 15) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White] Announcements Lab 9 is out


  1. http://www.cs.cornell.edu/courses/cs1110/2018sp Lecture 17: Classes (Chapter 15) CS 1110 Introduction to Computing Using Python [E. Andersen, A. Bracy, D. Gries, L. Lee, S. Marschner, C. Van Loan, W. White]

  2. Announcements • Lab 9 is out (just 2 of the 4 problems) • IMPORTANT: A3 updates on website! • More recursion examples, see the demos: § http://www.cs.cornell.edu/courses/cs1110/2014sp/lectures/index.php § https://www.cs.cornell.edu/courses/cs1110/2016fa/lectures/10-18- 16/modules/morefun.py • More daily practice: download the demo code we post for each lecture; remove the contents, and try to reproduce what we did in class. Or try to modify it in new ways. 2

  3. Recall: Objects as Data in Folders • An object is like a manila folder unique • Contains other variables identifier § Variables are called attributes type § Can change attribute values id1 nums (w/ assignment statements) id1 list • Has a “tab” that identifies it 2 0 § Unique number assigned by Python 7 3 1 § Fixed for lifetime of the object 5 2 • Has a type listed in the corner nums = [2,3,5] nums[1] = 7 3

  4. Classes are user-defined Types Classes are how we add Example Classes new types to Python • Point3 class name • Card • Rect id2 • Person Point3 2 x 3 y 5 z 4

  5. Simple Class Definition class < class-name > (): """Class specification""" < function definitions > 5

  6. The Class Specification Short class Worker(): 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] boss: Worker's boss. [Worker, or None if no boss] Attribute 0.. 999999999 means from 0 to 999999999, inclusive This is handy notation, not Python. Name 6

  7. Constructors • Function to create new instances § function name is the class name § Created for you automatically id8 • Calling the constructor: id8 w Worker § Makes a new object folder lname 'Andersen' § Initializes attributes (see next slide) ssn 1234 § Returns the id of the folder boss None w = Worker('Andersen', 1234, None) 7

  8. Special Method: __init__ two underscores ß called by the constructor def __init__(self, last_name, ssn, boss): """Initializer: creates a Worker Has last_name, ssn, and boss id8 Worker Pre: last_name a string, ssn an int in range 0..999999999, and boss either lname 'Erik' a Worker or None. ssn 1234 use self to self.lname = last_name assign boss None self.ssn = ssn attributes self.boss = boss w = Worker('Andersen', 1234, None) # this is the call to the constructor # the constructor calls __init__ 8

  9. Evaluating a Constructor Expression Worker('Erik', 1234, None) 1. Creates a new object (folder) of the class Worker on the heap id8 § Folder is initially empty Worker 2. Executes the method __init__ § self = folder name = identifier lname 'Erik' § Other arguments passed in order ssn 1234 § Executes commands in initializer boss None 3. Returns folder name, the identifier 9

  10. 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 ints § RGB class: all attributes must be ints in 0..255 • Purpose of the class specification 10

  11. Checking Invariants with an Assert class Student(): """Instance is a student taking python""" def __init__(self, name, NetID, is_auditing): """Initializer: instance with name, NetID, auditing status name: student's full name [str] NetID: student's NetID [str], 2-3 letters + 1-4 numbers is_auditing: whether student is auditing the class [bool]""" assert type(name) == str, "name should be type str" assert type(NetID) == str, "NetID should be type str" assert type(is_auditing) == bool, "is_auditing should be type bool" self.name = name self.NetID = NetID self.is_auditing = is_auditing 11

  12. Class Attributes Class Attributes: Variables that belong to the Class • One variable for the whole Class • Shared by all object instances • Access by <Class Name>.<attribute-name> Why? • Some variables are relevant to every object instance of a class • Does not make sense to make them object attributes • Doesn’t make sense to make them global variables, either Example: Suppose we want to keep track of how many students are enrolled in CS 1110 12

  13. Class Variables for CS1110 class Student(): Where does this variable live??? """Instance is a student taking python""” enrollment = 0 def __init__(self, name, NetID, is_auditing): """Initializer: instance with name, NetID, auditing status name: student's full name [str] NetID: student's NetID [str], 2-3 letters + 1-4 numbers is_auditing: whether student is auditing the class [bool]""" self.name = name self.NetID = NetID self.is_auditing = is_auditing Student.enrollment = Student.enrollment + 1 13

  14. Classes Have Folders Too Object Folders Class Folders • Separate for each instance • Data common to all instances • Example: 2 Student objects Student id1 id1 p1 Student enrollment 2 id2 name Jon Li p2 NetID jl200 True is_auditing • Not just data! id2 • Everything common to all Student instances goes here! name Jill Ba NetID jb110 14 is_auditing False

  15. Recall: Objects can have Methods Function: call with object as argument id1 Student <function-name>(<arguments>) name Jon Li len(my_list) NetID jl200 Method : function tied to the object True is_auditing <object-variable>.<function-call> my_list.count(7) • Attributes live in object folder Student • Class Attributes live in class folder enrollment 2 • Methods live in class folder __init__(self, name, NetID, is_auditing) 15

  16. Complete Class Definition keyword class Beginning of a class definition class < class-name > (): Specification """Class specification""" (similar to one for a function) < assignment statements > Student to define < function definitions > enrollment 0 class variables __init__(self, name, NetID, is_auditing) class Student(): to define methods """Specification goes here.""” Python creates enrollment = 0 after reading the def __init__(self, last_name, ssn, boss): class definition 16 . . . <snip> . . .

  17. Student Method Definitions enrollment 0 __init__(self, …) • Looks like a function def greet(self) § But indented inside class class Student(): § 1 st parameter always self def __init __(self, name, NetID, is_auditing): self.name = name Example: p1.greet() self.NetID = NetID self.is_auditing = is_auditing § Go to class folder for p1 Student.enrollment = Student.enrollment + 1 (i.e., Student) that’s where greet is defined def greet(self): """Prints information about the § Now greet is called with p1 Student to the screen""" as its first argument print("Hi! My name is "+ self.name) § This way, greet knows which print(”My NetID is "+ self.NetID) instance of Student it is if self.is_auditing: working with print("I'm auditing the class") 17

  18. Class Gotchas… and how to avoid them Rules to live by: 1. Refer to Class Variables using the Class Name s1 = Student(“Jon Li”, “jl200”, True) print(“current enrollment = “+str( Student.enrollment )) 2. Don’t forget self 18

  19. Name Resolution for Objects id1 id1 • ⟨ object ⟩ . ⟨ name ⟩ means s1 Student name Jon Li § Go the folder for object NetID jl200 § Find attribute/method name True is_auditing § If missing, check class folder § If not in either, raise error s1 = Student(“Jon Li”, “jl200”, True) Student # finds attribute in object folder enrollment 1 print(s1.name) __init__(self, name, # finds attribute in class folder NetID, is_auditing) print(s1.enrollment) ß dangerous 19

  20. Accessing vs. Modifying Class Variables • Recall: you cannot assign to a global variable from inside a function call • Similarly: you cannot assign to a class attribute from “inside” an object variable s1 = Student(“Jon Li”, “jl200”, True) Student.enrollment = 2 # updates class variable s1.enrollment = 9 # creates new object # variable called enrollment Better to refer to Class Variables using the Class Name 20

  21. What gets Printed? (Q) import cs1110 A: B: 1 1 s1 = cs1110.Student(“Jon Li”, “jl200”, True) 2 2 print(s1.enrollment) 3 3 s2 = cs1110.Student(“Jill Bo”, “jb20”, False) 3 3 print(s2.enrollment) 3 2 s2.enrollment = 3 print(s1.enrollment) C: D: print(s2.enrollment) print(cs1110.Student.enrollment) 1 1 2 1 2 3 3 3 2 3 21

  22. What gets Printed? (A) import cs1110 A: B: 1 1 s1 = cs1110.Student(“Jon Li”, “jl200”, True) 2 2 print(s1.enrollment) 3 3 s2 = cs1110.Student(“Jill Bo”, “jb20”, False) 3 3 print(s2.enrollment) 3 2 s2.enrollment = 3 print(s1.enrollment) C: D: print(s2.enrollment) print(cs1110.Student.enrollment) 1 1 2 1 2 3 What?!?&%$?? 3 3 Look at that in the Python Tutor. 2 3 22

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend