Classes and Objects, Part 1 Victor Norman CS104. Reading Quiz, Q1 A class definition define these two elements. A. attributes and functions B. attributes.

Slides:



Advertisements
Similar presentations
Section 6.1 CS 106, Fall The Big Q What do we get by being able to define a class?! Or Do we really need this?!
Advertisements

13-Jun-14 OOP features of Jeroo. Overview In this presentation we will discuss these topics: OOP terminology Jeroo syntax constructors methods.
Basic Object-Oriented concepts. Concept: An object has behaviors In old style programming, you had: –data, which was completely passive –functions, which.
CS104: Chapter 15 CS 104 Students and me. Big Question Q: You say creating a class is how to create a new type. Why would we even want to do this?! A:
CIT 590 Intro to Programming Classes. Schedule change The upcoming HW (HW6) is your last major Python HW. It will involve object oriented programming.
OBJECT ORIENTED PROGRAMMING (OOP) IN PYTHON David Moodie.
Lilian Blot TOWARDS MORE ADVANCED CONCEPTS & OBJECT ORIENTED PROGRAMMING Building Data Structure Autumn 2014 TPOP 1.
Road Map Introduction to object oriented programming. Classes
1 Programming for Engineers in Python Autumn Lecture 5: Object Oriented Programming.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
25-Jun-15 Starting Classes and Methods. Objects have behaviors In old style programming, you had: data, which was completely passive functions, which.
James Tam Classes and Objects You will learn how to define new types of variables.
Strings Victor Norman CS104 Calvin College. Reading Quiz Counts toward your grade.
Week 3 Recap CSE 115 – Fall Java Source Code File Made up of: Package declaration Class definition.
Slide 1. Slide 2 Administrivia Nate's office hours are Wed, 2-4, in 329 Soda! TA Clint will be handing out a paper survey in class sometime this week.
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
Computer Science 111 Fundamentals of Programming I Introduction to Programmer-Defined Classes.
Guide to Programming with Python
REFERENCES: CHAPTER 8 Object-Oriented Programming (OOP) in Python.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Centre for Computer Technology ICT115 Object Oriented Design and Programming Week 2 Intro to Classes Richard Salomon and Umesh Patel Centre for Information.
Inheritance. Inhertance Inheritance is used to indicate that one class will get most or all of its features from a parent class. class Dog(Pet): Make.
Turtle Graphics Victor Norman CS104 Calvin College.
Lists in Python.
Tutorial 2 Variables and Objects. Working with Variables and Objects Variables (or identifiers) –Values stored in computer memory locations –Value can.
Lecture Set 11 Creating and Using Classes Part B – Class Features – Constructors, Methods, Fields, Properties, Shared Data.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Files Victor Norman CS104. Reading Quiz, Q1 A file must be ___________ before a program can read data from it. A. accessed B. unlocked C. opened D. controlled.
Classes and Objects The basics. Object-oriented programming Python is an object-oriented programming language, which means that it provides features that.
DATA STRUCTURES LAB 1 TA: Nouf Al-harbi
Agenda Object Oriented Programming Reading: Chapter 14.
Built-in Data Structures in Python An Introduction.
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
PYTHON OBJECTS & CLASSES. What is an object? The abstract idea of anything What is in an object: Attributes Characteristics Represented by internal variables.
Chapter Object Oriented Programming (OOP) CSC1310 Fall 2009.
CSCI 6962: Server-side Design and Programming JSF DataTables and Shopping Carts.
Object-Oriented Programming © 2013 Goodrich, Tamassia, Goldwasser1Object-Oriented Programming.
Guide to Programming with Python Chapter Eight (Part I) Object Oriented Programming; Classes, constructors, attributes, and methods.
Section 6.1 CS 106 Victor Norman IQ Unknown. The Big Q What do we get by being able to define a class?! Or Do we really need this?!
Python – May 19 Review –What is the difference between: list, tuple, set, dictionary? –When is it appropriate to use each? Creating our own data types:
More Sequences. Review: String Sequences  Strings are sequences of characters so we can: Use an index to refer to an individual character: Use slices.
Classes and Objects, Part 1 Victor Norman CS104. “Records” In Excel, you can create rows that represent individual things, with each column representing.
Chapter 17 Q and A Victor Norman, et al. CS104. What is Object-oriented Programming? Q: What is object-oriented programming? A: It means defining classes/objects,
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Q and A for Sections 6.2, 6.3 Victor Norman CS106.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
OCR Computing GCSE © Hodder Education 2013 Slide 1 OCR GCSE Computing Python programming 3: Built-in functions.
Object-Oriented Programming (OOP) in Python References: Chapter 8.
Classes CS 162 (Summer 2009). Parts of a Class Instance Fields Methods.
CSC 108H: Introduction to Computer Programming Summer 2011 Marek Janicki.
CMSC201 Computer Science I for Majors Lecture 25 – Classes
Andrew(amwallis) Classes!
CS-104 Final Exam Review Victor Norman.
Copyright (c) 2017 by Dr. E. Horvath
Anatomy of a class Part I
CMPE212 – Stuff… Exercises 4, 5 and 6 are all fair game now.
To Get Started Paper sheet
User Defined Classes CS F.
Teach A-Level Computer Science: Object-Oriented Programming in Python
Object Oriented Programming in Python
ARRAYS 1 GCSE COMPUTER SCIENCE.
An Introduction to Object Orientated Programming
Object-Oriented Programming
EE 194/BIO 196: Modeling,simulating and optimizing biological systems
Programming For Big Data
Making our own Classes and objects
Migrating to Object-Oriented Programs
Anatomy of a class Part I
Classes and Methods 15-Aug-19.
Creating and Using Classes
Presentation transcript:

Classes and Objects, Part 1 Victor Norman CS104

Reading Quiz, Q1 A class definition define these two elements. A. attributes and functions B. attributes and properties C. functions and methods D. attributes and methods

Reading Quiz, Q2 In code written in a class definition, the following parameter is used to refer to the object: A.__init__ B.self C.this D.attribute

Reading Quiz, Q3 Given the following class definition, which line of code creates a new object? class Car: def __init__(self, make, model): self._make = make self._model = model A.Car.__init__(car, “Honda”, “Accord”) B.car = Car.__init__(self, “Honda”, “Accord”) C.car = __init__(Car, “Honda”, “Accord”) D.None of the above.

“Records” In Excel, you can create rows that represent individual things, with each column representing some property of that thing. E.g., each row could represent a student, with – column 1: student id – column 2: student last name – column 3: student first name – column 4: gpa – column 5: how much tuition is owed… Each row *must* stay together: don’t want to move values from one row to another.

How to do this in python? How could we make a collection of items/values that belong together? – Have to use a composite data type. – i.e., lists or tuples. Question: does order of items/values really matter?

Ancient History (last Thursday) A card is a tuple with 2 parts, a suit (one of “s”, “d”, “c”, “h”) and a number (2 – 14). We create a card by making a tuple. We access the suit via card[0] and number via card[1]. What is good and what is bad about this implementation?

What types of variables can we make? Is this good enough? Wouldn’t it be nice if we could create our own types?

Big Question What defines a type? Data + operations – what you can store. – what you can do to or with it.

Terminology a class is like a recipe (or template). – you don't eat the recipe, right? an object is an instantiation of that class – that's what you eat. Or, a class is a new type. Each class is defined by its – name – attributes (characteristics, properties, fields) – methods (functions) We already know how to define functions, but we don’t know how to group them together, to say, “These belong together, and they operate on this data.”

Using a List/Tuple to store data If we want to group together data into one structure/record, we could use a list (or a tuple): student1 = [‘Dan’, 4, [80, 82, 6]] student2 = [‘Paula’, 2, [49, 90, 87]] Disadvantages: – Looking at the list, cannot tell what the “fields” mean. (What is the 1th item?) – List has order, which we don’t need.

One fix: use functions We could create functions to extract and name the data: def getName(stud): return stud[0] def getYear(stud): return stud[1] def getLowestGrade(stud): # code here to iterate through stud[2] name = getName(student1) year = getYear(student2) if getLowestGrade(student1) > getLowestGrade(student2): print “Good job, student!”

Thoughts on this… It is a big improvement, but… Change the order of the data in the list  you have to change the function code. What is stud[1]? The code in the functions is still unreadable. (First grade is stud[2][0].) You cannot enforce that users of this list will use the provided functions to get the values. First parameter to every function is the student data structure.

Better: classes and objects a class is like a recipe (or template). – you don't eat the recipe, right? an object is an instantiation of that class – that's what you eat. Or, a class is a new type. Each class is defined by its – name – attributes (characteristics, properties, fields) – methods (functions) We already know how to define functions, but we don’t know how to group them together, to say, “These belong together, and they operate on this data.”

Examples list is a built-in python class. – holds ordered objects. – has methods defined: append(), extend(), index(), [], [x:y], +, pop(), etc. Instantiate it as often as you want. girls = [‘Kim’, ‘Taylor’, ‘Beyonce’] guys = [‘Stone’, ‘Rock’, ‘Lance’]

Attributes and Methods Attribute: a “field” in an object. – A.k.a. a characteristic, property, or an instance variable. – a “noun”: something an object “has”. Method: Operation/function you ask an object to do to itself. – it is a verb.

Clicker Q Which of the following is not a good attribute name of a Car? A.numWheels B.accelerate C.color D.year E.manufacturer

Clicker Q2 Which of the following is not a good method name of a Person class? A.hairColor B.speak C.climbStairs D.walk E.jump

Syntax to do all this Need to define the class… – name – attributes of an object – methods that can be called to operate on the object.

Syntax of class definition class Student: # use Capital Letter “””A class that represents a Student.””” def __init__(self, name, year, grades): “””Constructor to make a new students instance (object).””” self.myName = name self.myYear = year self.myGrades = grades student1 = Student( “Dan”, 4, [80, 82, 6] ) First, define how to create an instance of a Student class. Assign given parameter values to attributes in new object. self is the new instance (object) being created and initialized

self Note that there is code “on the inside” – code inside the class definition. Code in __init__, getName(), etc. This code refers to the object as self. Then, there is code on the outside: stud1 = Student( “Dan”, 4, [100, 90, 80] ) This code refers to the object as stud1 (or whatever variable refers to the object).

Differences from using a list fields have clear names! –self.name is the student’s name, instead of stud[0]. fields are not stored in any order: just “owned” by the object.

cs104Student.click() How many syntax errors are there in this code?: class Car def _init_(make, model, year): self.myMake = make self.myModel = model myYear = year

cs104Student.clickAgain() Given this class definition: class Car: def __init__(self, make, model, year): self.myMake = make self.myModel = model self.myYear = year which is legal code to make a new Car instance? A.aCar = Car.__init__(self, “Honda”, “Odyssey”, 2001) B.aCar = Car.__init__("Honda", "Odyssey", 2001) C.aCar = Car("Honda", "Odyssey", 2001) D.aCar = Car(self, "Honda", "Odyssey", 2001) E.Car(aCar, "Honda", "Odyssey", 2001)

getters/accessors and setters/mutators First methods typically written are to allow code that uses the class to access/change the attributes: If you define attribute xyz, you create: def getXyz(self): “”“return the xyz value for this object””” return self.xyz def setXyz(self, newXyz): “””set the attribute xyz to the new value””” self.xyz = newXyz

Example class Student: def __init__(self, name, year, grades): self.myName = name self.myYear = year def getName(self): return self.myName def setName(self, newName): self.myName = newName def getYear(self): return self.myYear def setYear(self, newYear): self.myYear = newYear # Create a student student1 = Student( “Angelina”, 10, [] )

Example Continued # Old Code: name = getName(student1) year = getYear(student2) if getLowestGrade(student1) > getLowestGrade(student2): print “Good job, student!” # Now: name = student1.getName() year = student2.getYear() if student1.getLowestGrade() > student2.getLowestGrade(): print “God job, student!” self “inside” the code

If there is time… List 8 properties you might want to store about a Car. List the type of each property. Write the first line of the class definition, and the constructor. The constructor initializes attributes to given values. Write a getter method for each of 2 attributes. Write a setter method for 2 attributes that can be changed.