What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010

Size: px
Start display at page:

Download "What is a Class? Short Answer. Responding to Messages. Everything in Python is an Object 11/8/2010"

Transcription

1 The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 11 Introduction to Classes class Student(object): """Simple Student class.""" def init (self,first='', last='', id=0): # init instance self.firstnamestr = first self.lastnamestr = last self.idint = id def str (self): # string rep, e.g. for printing return "%s %s, ID:%s" % \ (self.firstnamestr, self.lastnamestr, self.idint) Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 1 2 What is a Class? Short Answer If you have done anything in computer science before, you likely will have heard the term object oriented programming (OOP) What is OOP, and why should I care? The short answer is that object oriented programming is a way to think about objects in a program (such as variables, functions, etc). A program becomes less a list of instructions and more a set of objects and how they interact. 3 4 Responding to Messages As a set of interacting objects, each object responds to messages sent to it. The interaction of objects via messages makes a high level description of what the program is doing. Everything in Python is an Object In case you hadn t noticed, everything in Python is an object. Thus Python embraces OOP at a fundamental level. Start! 5 6 1

2 OOP Helps in Software Engineering Software engineering is the discipline of managing code to ensure its long-term use. Remember, SE via refactoring: takes existing code and modifies it makes the overall code simpler, easier to understand doesn t change the functionality, only the form! More Refactoring Hiding the details of what the message entails means that changes can be made to the object and the flow of messages (and their results) can stay the same. Thus the implementation of the message can change but its intended effect stays the same. This is encapsulation. 7 8 OOP Principles Encapsulation: hiding design details to make the program clearer and more easily modified later. Modularity: the ability to make objects stand alone so they can be reused (our modules). I.e. the math module. Inheritance: create a new object by inheriting (like father to son) many object characteristics while creating or over-riding for this object. Polymorphism: (hard) Allow one message to be sent to any object and have it respond appropriately based on the type of object it is. Class versus Instance One of the harder things to understand is what a class is and what an instance of a class is. Consider the analogy of the cookie cutter and a cookie Template versus Exemplar The cutter is a template for stamping out cookies, the cookie is what is made each time the cutter is used. One template can be used to make an infinite number of cookies, each one just like the other. No one confuses a cookie for a cookie cutter, do they? Same in OOP You define a class as a way to generate new instances of that class. Both the instances and the classes are themselves objects. The structure of an instance starts out the same, as dictated by the class. The instances respond to the messages defined as part of the class

3 OK, a Different Tack Theory of Forms Ever hear of Plato? the second western philosopher B.C, in Greece (Athens) student of Socrates (the first western philosopher), teacher of Aristotle prolific writer and first of the Greek philosophers we have writings from Plato worried about the problem of universals. For example, Have you ever seen a perfect circle? Probably not; nearly any circle I were to draw (even given great care) would be flawed in some way So what is Circleness? Forms So if you have never seen a perfect circle, how do you know one when you see one? We assume that somehow we can compare our experiences to some universal (a perfect circle), but how can we compare to something we have never seen? Plato assumed there must be some universal concepts that we, as cognitive humans, could participate in (we could think about) that would allow us to compare particulars to universals. He called these universals the Forms And, um, How does that Help? Why a Class? In a way, OOP is related to a Form view of the world: instances are made in the image of its class though an instance may change (no longer be a perfect class instance) it is still an instance of the class (its form) See, ancient philosophy comes to the rescue! We make classes because we need more complicated, user-defined data types to construct instances we can use. Each class has potentially two aspects: the data (types, number, names) that each instance might contain the messages that each instance can respond to

4 A First Class Constructor When a class is defined, a function is made with the same name as the class This function is called the constructor. By calling it, you can create an instance of the class. We can affect this creation (more later), but by default Python can make an instance. dir Function class myclass (object): pass myinstance = myclass() #call constructor dir(myinstance) [' class ', ' delattr ', ' dict ', ' doc ', ' format ', ' getattribute ', ' hash ', ' init ', ' module ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' setattr ', ' sizeof ', ' str ', ' subclasshook ', ' weakref '] Dot Reference We can refer to the attributes of an object by doing a dot reference, of the form: object.attribute The attribute can be a variable or a function. It is part of the object, either directly or by that object being part of a class. Examples print myinst.myval print a variable associated with the object myinst myinst.mymethod() call a method associated with the object myinst Variable versus method, you can tell by the parenthesis at the end of the reference

5 How to Make an Object-Local Value Once an object is made, the data is made the same way as in any other Python situation, by assignment. Any object can thus be augmented by adding a variable: myinst.instanceattribute = hello New Attribute Shown in dir dir(myinstance) [' class ', ' delattr ', ' dict ', ' doc ', ' format ', ' getattribute ', ' hash ', ' init ', ' module ', ' new ', ' reduce ', ' reduce_ex ', ' repr ', ' setattr ', ' sizeof ', ' str ', ' subclasshook ', ' weakref, instanceattribute] A Class is a New Type Class Instance Relationship mylst = [1, 2, 3] type(mylst) => type< list > mystr = abc type(mystr) => type< str > class myclass (object): pass myinstance = myclass() type(myinstance) => type<class main.myclass> Instance Knows its Class Because each instance has as its type the class that it was made from, an instance remembers its class. This is often called the instance-of relationship

6 Scope Local in the Instance We saw in Chapter 7 how scope works. It works differently in the class system, taking advantage of the instance-of relationship. Assignment to the instance makes the variable local: class myclass(object): pass myinst = myclass() myinst.myvar = 12 print myinst.myvar # prints Look Up the Instance-Of Link If the attribute is not stored in the instance, Python looks up the instance-of link to see if it is stored in the associated class. Look in the Class class myclass(object): myvar = 100 myinst = myclass() print myinst.myvar # prints Local Assignment Before Class This mix can lead to some tricky stuff: class myclass(object): myvar = 100 Methods myinst = myclass() yourinst = myclass() myinst.myvar = -1 print myinst.myvar # prints -1 print yourinst.myvar# prints 100 myclass.myvar = 500 print myinst.myvar # prints -1 print yourinst.myvar# prints

7 class myclass (object): classattribute = 'world' Code Listing 11.2 def mymethod (self, param1): print '\nhello %s' % (param1) print 'The object calling this method is: %s' %\ str(self) self.instanceattribute = param1 myinstance = myclass() print "output of dir(myinstance):" print dir(myinstance) myinstance.mymethod('world') print "Instance has new attribute with value: %s" %\ myinstance.instanceattribute Method versus Function Discussed before, a method and a function are closely related. They are both small programs that have parameters, perform some operation and (potentially) return a value. The main difference is that methods are functions tied to a particular object. Difference in Calling Functions are called, methods are called in the context of an object: function: dosomething(param1) method: anobject.dosomething(param1) This means that the object that the method is called on is always implicitly a parameter! Difference in Definition Methods are defined inside the suite of a class. Methods always bind the first parameter in the definition to the object that called it. This parameter can be named anything, but traditionally it is named self: class myclass(object): def mymethod(self,param1): dosomething More on Self self is an important variable. In any method it is bound to the object that called the method. Through self, we can access the internal structure of the instance

8 Back to the example class myclass (object): classattribute = 'world' def mymethod (self, param1): print '\nhello %s' % (param1) print 'The object calling this method is: %s \ str(self) self.instanceattribute = param1 Binding self newinstance = myclass() newinstance.printit() def myclass (object): def printit(self): self is Bound for Us When a dot method call is made, the object that called the method is automatically assigned to self. We can use self to remember, and therefore refer, to the calling object. To reference any part of the calling object, we must always precede it with self. The method can be written generically, dealing with all calling objects through self Writing a class Code Listing

9 class Student(object): def init (self,first='', last='', id=0): self.firstnamestr = first self.lastnamestr = last self.idint = id def update(self,first='',last='',id=0): if first: self.firsnamestr = first if last: self.lastnamestr = last if id: self.idint = id def str (self): return "%s %s, ID:%s" % \ (self.firstnamestr, self.lastnamestr, self.idint) Constructor There are some special methods that have certain pre-defined roles for all classes. One of the first we will learn is a constructor. Constructor is called when an instance is made and provides the class designer the opportunity to set up the instance with variables, by assignment Calling a Constructor Special Python Keywords As mentioned, a constructor is called by using the name of the class as a function call (by adding () after the class name): myinst = myclass() Creates a new instance using myclass. Again, Python has special uses for keywords that begin and end with. so far we have seen the doc attributed of a function with a doc string. In classes, we will see more of these special values The init Method One of the special method names in a class is the constructor name, init. By assigning values in the constructor, every instance will start out with the same variables. You can also pass arguments to a constructor through its init method. def init (self,first='', last='', id=0): self.firstnamestr = first self.lastnamestr = last self.idint = id self is bound to the default instance as it is being made. If we want to add an attribute to that instance, we modify the attribute associated with self

10 Default Constructor If you don t provide a constructor then only the default constructor is provided. The default constructor does system stuff to create the instance, nothing more. You cannot pass arguments to the default constructor Every Class Should Have init By providing the constructor, we ensure that every instance, at least at the point of construction, is created with the same contents. This gives us some control over each instance. def str (self): Printing return "%s %s, ID:%s" % \ (self.firstnamestr, self.lastnamestr, self.idint) What happens when we call print myinst? This is assumed, by Python, to be a call to convert the instance to a string, which is the str method. In the method, myinst is bound to self, and printing then occurs using that instance Now There are Three Class Designer There are now three groups in our coding scheme: user programmer, class user programmer, class designer The class designer is creating code to be used by other programmers. In so doing, the class designer is making a kind of library that other programmers can take advantage of

11 OOP Helps in Software Engineering Point Class, Code Listings Software engineering is the discipline of managing code to ensure its long-term use. Remember, SE via refactoring: takes existing code and modifies it makes the overall code simpler, easier to understand doesn t change the functionality, only the form! More Refactoring Hiding the details of what the message entails means that changes can be made to the object and the flow of messages (and their results) can stay the same. Thus the implementation of the message can change but its intended effect stays the same. This is encapsulation. OOP Principles Encapsulation: hiding design details to make the program clearer and more easily modified later. Modularity: the ability to make objects stand alone so they can be reused (our modules). I.e. the math module. Inheritance: create a new object by inheriting (like father to son) many object characteristics while creating or over-riding for this object. Polymorphism: (hard) Allow one message to be sent to any object and have it respond appropriately based on the type of object it is We are Still at Encapsulation Features of encapsulation: - hid details of the implementation so that the program was easier to read and write - modularity: make an object so that it can be reused in other contexts - providing an interface (the methods) that are the approved way to deal with the class Private Values

12 Class Namespaces are Dicts The namespaces in every object and module is indeed a namespace. That dictionary is bound to the special variable dict. It lists all the local vals (variables, functions) in the object. Example Namespace class myclass(object): x = 100 def mymethod(param1=500): print param1 >>> myclass. dict.items() [(' module ', ' main '), ('mymethod', <function mymethod at 0x12200f0>), (' dict ', <attribute ' dict ' of 'myclass' objects>), ('x', 100), (' weakref ', <attribute ' weakref ' of 'myclass' objects>), (' doc ', None)] Private Variables in an Instance Many OOP approaches allow you to make a variable or function in an instance private. Private means not accessible by the class user, only the class developer. There are advantages to controlling who can access the instance values. Privacy in Python Python takes the approach We are all adults here. No hard restrictions. Provides naming to avoid accidents. Use in front of any variable This mangles the name to include the class, namely var becomes _class var. Still fully accessible, and the dict makes it obvious Privacy Example class myclass(object): def init (self,p1='firstparam',p2='secondpa ram'): self.var1=p1 self. var2=p2 myinst = myclass() myinst. dict.items() [('_myclass var2', 'secondparam'), ('var1', 'firstparam')] 71 12

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes

What is a class? Responding to messages. Short answer 7/19/2017. Code Listing 11.1 First Class. chapter 11. Introduction to Classes chapter 11 Code Listing 11.1 First Class Introduction to Classes What is a class? If you have done anything in computer science before, you likely will have heard the term object oriented programming (OOP)

More information

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Haleh Ashki 2015, updated Peter Beerli 2017 Traditionally, a program has been seen as a recipe a set of instructions that you follow from start to finish in order to complete

More information

Object Oriented Programming. Feb 2015

Object Oriented Programming. Feb 2015 Object Oriented Programming Feb 2015 Tradi7onally, a program has been seen as a recipe a set of instruc7ons that you follow from start to finish in order to complete a task. That approach is some7mes known

More information

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013

Classes, part Deux. Three Groups. CSE 231, Rich Enbody. Users Programmers Class Designers 11/11/13. Michigan State University CSE 231, Fall 2013 , part Deux CSE 231, Rich Enbody Three Groups Users Programmers Class Designers 1 Getters and Setters getters: methods that fetch the value setters: methods set a value 2 GetterSetter Example Why do this?

More information

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012

CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures. Jom Magrotker UC Berkeley EECS July 12, 2012 CS61A Lecture 15 Object Oriented Programming, Mutable Data Structures Jom Magrotker UC Berkeley EECS July 12, 2012 COMPUTER SCIENCE IN THE NEWS http://www.iospress.nl/ios_news/music to my eyes device converting

More information

Positional, keyword and default arguments

Positional, keyword and default arguments O More on Python n O Functions n Positional, keyword and default arguments in repl: >>> def func(fst, snd, default="best!"):... print(fst, snd, default)... >>> func(snd='is', fst='python') ('Python', 'is',

More information

The Practice of Computing Using PYTHON

The Practice of Computing Using PYTHON The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures

More information

Chapter 12 Object-Oriented Programming. Starting Out with Games & Graphics in C++ Tony Gaddis

Chapter 12 Object-Oriented Programming. Starting Out with Games & Graphics in C++ Tony Gaddis Chapter 12 Object-Oriented Programming Starting Out with Games & Graphics in C++ Tony Gaddis Addison Wesley is an imprint of 2010 Pearson Addison-Wesley. All rights reserved. 12.1 Procedural and Object-Oriented

More information

Intro. Scheme Basics. scm> 5 5. scm>

Intro. Scheme Basics. scm> 5 5. scm> Intro Let s take some time to talk about LISP. It stands for LISt Processing a way of coding using only lists! It sounds pretty radical, and it is. There are lots of cool things to know about LISP; if

More information

Data Structures (list, dictionary, tuples, sets, strings)

Data Structures (list, dictionary, tuples, sets, strings) Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in brackets: l = [1, 2, "a"] (access by index, is mutable sequence) Tuples are enclosed in parentheses: t = (1, 2, "a") (access

More information

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace

User Defined Types. Babes-Bolyai University Lecture 06. Lect Phd. Arthur Molnar. User defined types. Python scope and namespace ? User Defined Types Babes-Bolyai University arthur@cs.ubbcluj.ro Overview? 1? 2 3 ? NB! Types classify values. A type denotes a domain (a set of values) operations on those values. ? Object oriented programming

More information

Programming Paradigms in Python

Programming Paradigms in Python Programming Paradigms in Python Johan Falkenjack February 5, 2018 Programming Paradigms An overarching philosophy about programming Execution model Code organization Most famous paradigms: Imperative (write

More information

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017 Overview of OOP Dr. Zhang COSC 1436 Summer, 2017 7/18/2017 Review Data Structures (list, dictionary, tuples, sets, strings) Lists are enclosed in square brackets: l = [1, 2, "a"] (access by index, is mutable

More information

What is a function? "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

What is a function? The Practice of Computing Using Python, Punch & Enbody, Copyright 2013 Pearson Education, Inc. Functions Husni What is a function? "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc. Functions From Mathematics we know that functions perform some operation

More information

Working with Strings. Husni. "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc.

Working with Strings. Husni. The Practice of Computing Using Python, Punch & Enbody, Copyright 2013 Pearson Education, Inc. Working with Strings Husni "The Practice of Computing Using Python", Punch & Enbody, Copyright 2013 Pearson Education, Inc. Sequence of characters We've talked about strings being a sequence of characters.

More information

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The Practice of Computing Using PYTHON. Chapter 4. Working with Strings. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 4 Working with Strings 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Sequence of Characters We

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Fast Introduction to Object Oriented Programming and C++

Fast Introduction to Object Oriented Programming and C++ Fast Introduction to Object Oriented Programming and C++ Daniel G. Aliaga Note: a compilation of slides from Jacques de Wet, Ohio State University, Chad Willwerth, and Daniel Aliaga. Outline Programming

More information

Python OOP. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 19, 2010

Python OOP. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 19, 2010 Python OOP Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée October 19, 2010 Stéphane Vialette (LIGM, Université Paris-Est Marne-la-Vallée) Python OOP October 19, 2010 1 / 59 Outline 1 Introduction

More information

Object-Oriented Programming in Processing

Object-Oriented Programming in Processing Object-Oriented Programming in Processing Object-Oriented Programming We ve (kinda) been doing this since Day 1: Python is a deeply object oriented language Most of the data types we were using (strings,

More information

More Data Structures. What is a Dictionary? Dictionaries. Python Dictionary. Key Value Pairs 10/21/2010

More Data Structures. What is a Dictionary? Dictionaries. Python Dictionary. Key Value Pairs 10/21/2010 The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 8 Dictionaries and Sets More Data Structures We have seen the list data structure and its uses. We will now examine two, more

More information

6. Object-Oriented Programming, II. Programming and Algorithms II Degree in Bioinformatics Fall 2018

6. Object-Oriented Programming, II. Programming and Algorithms II Degree in Bioinformatics Fall 2018 6. Object-Oriented Programming, II Programming and Algorithms II Degree in Bioinformatics Fall 2018 Inheritance class Carnivora(Animal): class Canid(Carnivora): class Dog(Canid): class Husky(Dog): class

More information

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College August 29, 2018 Outline Outline 1 Chapter 2: Data Abstraction Outline Chapter 2: Data Abstraction 1 Chapter 2: Data Abstraction

More information

A Function that Calls Itself. It Doesn t Do Anything! Defining a Recursive Function. 2) Base Case. 1) Divide and Conquer 11/22/2010

A Function that Calls Itself. It Doesn t Do Anything! Defining a Recursive Function. 2) Base Case. 1) Divide and Conquer 11/22/2010 The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 16 Recursion: Another Control Mechanism A Function that Calls Itself The very basic meaning of a recursive function is a function

More information

CS1210 Lecture 28 Mar. 27, 2019

CS1210 Lecture 28 Mar. 27, 2019 CS1210 Lecture 28 Mar. 27, 2019 Discussion section exam scores posted score # people 0-5 6-10 11-15 16-20 21-25 26-30 28 48 39 37 30 9 median: 13 Some words about overall grades more detail next Wednesday

More information

Dangerously Advanced Python

Dangerously Advanced Python Dangerously Advanced Python Mike Verdone for Protospace, Calgary May 2009 http://mike.verdone.ca/ Introspection and Metaprogramming Introspection: Programs that can interrogate their own data structures

More information

Programming for Engineers in Python

Programming for Engineers in Python Programming for Engineers in Python Lecture 5: Object Oriented Programming Autumn 2011-12 1 Lecture 4 Highlights Tuples, Dictionaries Sorting Lists Modular programming Data analysis: text categorization

More information

Python in 10 (50) minutes

Python in 10 (50) minutes Python in 10 (50) minutes https://www.stavros.io/tutorials/python/ Python for Microcontrollers Getting started with MicroPython Donald Norris, McGrawHill (2017) Python is strongly typed (i.e. types are

More information

Chapter 11 Object and Object- Relational Databases

Chapter 11 Object and Object- Relational Databases Chapter 11 Object and Object- Relational Databases Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 11 Outline Overview of Object Database Concepts Object-Relational

More information

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal

COMSC-051 Java Programming Part 1. Part-Time Instructor: Joenil Mistal COMSC-051 Java Programming Part 1 Part-Time Instructor: Joenil Mistal Chapter 4 4 Moving Toward Object- Oriented Programming This chapter provides a provides an overview of basic concepts of the object-oriented

More information

Programming with Python

Programming with Python Programming with Python Lecture 3: Python Functions IPEC Winter School 2015 B-IT Dr. Tiansi Dong & Dr. Joachim Köhler Python Functions arguments return obj Global vars Files/streams Function Global vars

More information

Inherence and Nonsubstantial Particulars: An Object-Oriented View Samuel H. Kenyon

Inherence and Nonsubstantial Particulars: An Object-Oriented View Samuel H. Kenyon Inherence and Nonsubstantial Particulars: An Object-Oriented View Samuel H. Kenyon 09/29/04 Kenyon 2 Introduction In order to tackle the meanings, assumptions, and inconsistencies in Aristotle s Categories[1],

More information

Object Model Comparisons

Object Model Comparisons Object Model Comparisons 1 Languages are designed, just like programs Someone decides what the language is for Someone decides what features it's going to have Can't really understand a language until

More information

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation.

Be careful when deciding whether to represent data as integers or floats, and be sure that you consider all possible behaviors in computation. Table of Contents: 1. Integers and floats 2. for vs. while loops 3. Checking boolean conditions with if/else 4. Docstrings 5. Changing collections while iterating over them 6. Directly Accessing Instance

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python

About Python. Python Duration. Training Objectives. Training Pre - Requisites & Who Should Learn Python About Python Python course is a great introduction to both fundamental programming concepts and the Python programming language. By the end, you'll be familiar with Python syntax and you'll be able to

More information

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University

Lecture 3. COMP1006/1406 (the Java course) Summer M. Jason Hinek Carleton University Lecture 3 COMP1006/1406 (the Java course) Summer 2014 M. Jason Hinek Carleton University today s agenda assignments 1 (graded) & 2 3 (available now) & 4 (tomorrow) a quick look back primitive data types

More information

Day 2. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 2. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 2 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda a quick look back (Monday s class) assignments a1 is due on Monday a2 will be available on Monday and is due the following

More information

Chapter 8: Creating Your Own Type Classes

Chapter 8: Creating Your Own Type Classes Chapter 8: Creating Your Own Type Classes What we will learn: Object-oriented programming What is a class How to create a class Assigning values to a class What you need to know before: Data types Methods

More information

Java Object Oriented Design. CSC207 Fall 2014

Java Object Oriented Design. CSC207 Fall 2014 Java Object Oriented Design CSC207 Fall 2014 Design Problem Design an application where the user can draw different shapes Lines Circles Rectangles Just high level design, don t write any detailed code

More information

Polymorphism Part 1 1

Polymorphism Part 1 1 Polymorphism Part 1 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid

More information

x = e Python tries to avoid overwrites i Python tries to avoid overwrites next Monday Programming Assignment #7 on Prolog quarter Assignment Revisited

x = e Python tries to avoid overwrites i Python tries to avoid overwrites next Monday Programming Assignment #7 on Prolog quarter Assignment Revisited News Programming Assignment #6 is up, due next Monday Programming Assignment #7 on Prolog will be up soon and due at the end of the quarter Python tries to avoid overwrites n Python tries to ensure you

More information

Software Development Python (Part B)

Software Development Python (Part B) Software Development Python (Part B) Davide Balzarotti Eurecom 1 List Comprehension It is a short way to construct a list based on the content of other existing lists Efficient Elegant Concise List comprehensions

More information

Effective Programming Practices for Economists

Effective Programming Practices for Economists Effective Programming Practices for Economists 14. Object-oriented programming Hans-Martin von Gaudecker Department of Economics, Universität Bonn Revisiting abstractions Reminder of the example Reconsider

More information

Objects. say something to express one's disapproval of or disagreement with something.

Objects. say something to express one's disapproval of or disagreement with something. Objects say something to express one's disapproval of or disagreement with something. class Person: def init (self, name, age): self.name = name self.age = age p1 = Person("John", 36) class Person: def

More information

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1

The Three Rules. Program. What is a Computer Program? 5/30/2018. Interpreted. Your First Program QuickStart 1. Chapter 1 The Three Rules Chapter 1 Beginnings Rule 1: Think before you program Rule 2: A program is a human-readable essay on problem solving that also executes on a computer Rule 3: The best way to improve your

More information

Object Oriented Programming #10

Object Oriented Programming #10 Object Oriented Programming #10 Serdar ARITAN Biomechanics Research Group, Faculty of Sports Sciences, and Department of Computer Graphics Hacettepe University, Ankara, Turkey 1 Simple programming tasks

More information

Object-Oriented Python

Object-Oriented Python Object-Oriented Python Everything is an object. Every object has a value. a type. an identity. a namespace. CS105 Python def initstudent(student, eid): global A class is like a namespace. CS105 Python

More information

MITOCW watch?v=flgjisf3l78

MITOCW watch?v=flgjisf3l78 MITOCW watch?v=flgjisf3l78 The following content is provided under a Creative Commons license. Your support will help MIT OpenCourseWare continue to offer high-quality educational resources for free. To

More information

Outline. Outline. 1 Chapter 2: Data Abstraction

Outline. Outline. 1 Chapter 2: Data Abstraction Outline Outline 1 Chapter 2: Data Abstraction From Data Type to ADT Values A value is a unit of information used in a program. It can be associated with a constant or variable (a name) by an assignment

More information

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University Day 4 COMP1006/1406 Summer 2016 M. Jason Hinek Carleton University today s agenda assignments questions about assignment 2 a quick look back constructors signatures and overloading encapsulation / information

More information

Adapted from Code.org curriculum

Adapted from Code.org curriculum Adapted from Code.org curriculum Objectives Use the return command to design functions. Identify instances when a function with a return value can be used to contain frequently used computations within

More information

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. Ch. 14: Inheritance

More information

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an . Michigan State University CSE 231, Fall 2013

Getting Started. Office Hours. CSE 231, Rich Enbody. After class By appointment send an  . Michigan State University CSE 231, Fall 2013 CSE 231, Rich Enbody Office Hours After class By appointment send an email 2 1 Project 1 Python arithmetic Do with pencil, paper and calculator first Idle Handin Help room 3 What is a Computer Program?

More information

Functions. CSE 231, Rich Enbody. From Mathematics we know that functions perform some operation and return one value.

Functions. CSE 231, Rich Enbody. From Mathematics we know that functions perform some operation and return one value. Functions CSE 231, Rich Enbody From Mathematics we know that functions perform some operation and return one value. 2 1 Functions encapsulate the performance of some operation, so it can be used by others.

More information

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language

Chapter 11. Categories of languages that support OOP: 1. OOP support is added to an existing language Categories of languages that support OOP: 1. OOP support is added to an existing language - C++ (also supports procedural and dataoriented programming) - Ada 95 (also supports procedural and dataoriented

More information

Lecture 5. Introduction to Python! Lecture 5

Lecture 5. Introduction to Python! Lecture 5 Lecture 5 Introduction to Python Lecture 5 Summary OOP Concepts Object trees Classes Attributes Methods OOP OOP Inheritance Composition Allows a class to inherit the characteristics and behaviour as another

More information

Chapter 1: Object-Oriented Programming Using C++

Chapter 1: Object-Oriented Programming Using C++ Chapter 1: Object-Oriented Programming Using C++ Objectives Looking ahead in this chapter, we ll consider: Abstract Data Types Encapsulation Inheritance Pointers Polymorphism Data Structures and Algorithms

More information

Functions #5. Serdar ARITAN. Department of Computer Graphics Hacettepe University, Ankara, Turkey

Functions #5. Serdar ARITAN. Department of Computer Graphics Hacettepe University, Ankara, Turkey #5 Serdar ARITAN Department of Computer Graphics Hacettepe University, Ankara, Turkey 1 I have never considered Python to be heavily influenced by functional languages, no matter what people say or think.

More information

features of Python 1.5, including the features earlier described in [2]. Section 2.6 summarizes what is new in Python The class and the class

features of Python 1.5, including the features earlier described in [2]. Section 2.6 summarizes what is new in Python The class and the class A note on reection in Python 1.5 Anders Andersen y AAndersen@ACM.Org March 13, 1998 Abstract This is a note on reection in Python 1.5. Both this and earlier versions of Python has an open implementation

More information

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill

Chapter 12. OOP: Creating Object-Oriented Programs The McGraw-Hill Companies, Inc. All rights reserved. McGraw-Hill Chapter 12 OOP: Creating Object-Oriented Programs McGraw-Hill 2010 The McGraw-Hill Companies, Inc. All rights reserved. Chapter Objectives - 1 Use object-oriented terminology correctly Create a two-tier

More information

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1

What is Polymorphism? Quotes from Deitel & Deitel s. Why polymorphism? How? How? Polymorphism Part 1 Polymorphism Part 1 What is Polymorphism? Polymorphism refers to a programming language s ability to process objects differently depending on their data type or class. Number person real complex kid adult

More information

Chapter 2: Objects, classes and factories

Chapter 2: Objects, classes and factories Chapter 2 Objects, classes and factories By the end of this chapter you will have the essential knowledge to start our big project writing the MyPong application. This chapter is important for another

More information

Programming for Kids

Programming for Kids Programming for Kids Peter Armstrong This book is for sale at http://leanpub.com/programmingforkids This version was published on 2016-05-08 This is a Leanpub book. Leanpub empowers authors and publishers

More information

Data Abstraction. Hwansoo Han

Data Abstraction. Hwansoo Han Data Abstraction Hwansoo Han Data Abstraction Data abstraction s roots can be found in Simula67 An abstract data type (ADT) is defined In terms of the operations that it supports (i.e., that can be performed

More information

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University

Day 3. COMP 1006/1406A Summer M. Jason Hinek Carleton University Day 3 COMP 1006/1406A Summer 2016 M. Jason Hinek Carleton University today s agenda assignments 1 was due before class 2 is posted (be sure to read early!) a quick look back testing test cases for arrays

More information

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger

UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division. P. N. Hilfinger UNIVERSITY OF CALIFORNIA Department of Electrical Engineering and Computer Sciences Computer Science Division CS 164 Spring 2005 P. N. Hilfinger Project #2: Static Analyzer for Pyth Due: Wednesday, 6 April

More information

Object- Oriented Programming in Visual Basic.NET. Heng Sovannarith

Object- Oriented Programming in Visual Basic.NET. Heng Sovannarith Object- Oriented Programming in Visual Basic.NET Heng Sovannarith heng_sovannarith@yahoo.com IntroducCon OOP is a design philosophy. It stands for Object Oriented Programming. Object- Oriented Programming

More information

QUIZ. How could we disable the automatic creation of copyconstructors

QUIZ. How could we disable the automatic creation of copyconstructors QUIZ How could we disable the automatic creation of copyconstructors pre-c++11? What syntax feature did C++11 introduce to make the disabling clearer and more permanent? Give a code example. QUIZ How

More information

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

The Practice of Computing Using PYTHON. Chapter 2. Control. Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 2 Control 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Control: A Quick Overview 2 Selection

More information

Fundamental Concepts and Definitions

Fundamental Concepts and Definitions Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most

More information

Chapter 6 Introduction to Defining Classes

Chapter 6 Introduction to Defining Classes Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 16 Classes Prof. Jeremy Dixon Based on slides from http://www.csee.umbc.edu/courses/691p/notes/python/python3.ppt Last Class We Covered Review of Functions

More information

Intro. Classes & Inheritance

Intro. Classes & Inheritance Intro Functions are useful, but they're not always intuitive. Today we're going to learn about a different way of programming, where instead of functions we will deal primarily with objects. This school

More information

^l^s^^^^^^^^^^s^^^ ^.1^L^ gs *^gs (s^s^^^^s^^ ^S^^^^ls

^l^s^^^^^^^^^^s^^^ ^.1^L^ gs *^gs (s^s^^^^s^^ ^S^^^^ls THE PRACTICE OF COMPUTING USING ^l^s^^^^^^^^^^s^^^ ^.1^L^ gs *^gs (s^s^^^^s^^ ^S^^^^ls M&T M M mlklkmam sssr 'SSf iffy (*jw>> (ggu ^SBBfr

More information

Welcome to Design Patterns! For syllabus, course specifics, assignments, etc., please see Canvas

Welcome to Design Patterns! For syllabus, course specifics, assignments, etc., please see Canvas Welcome to Design Patterns! For syllabus, course specifics, assignments, etc., please see Canvas What is this class about? While this class is called Design Patterns, there are many other items of critical

More information

Lecture 19. Operators and Abstraction

Lecture 19. Operators and Abstraction Lecture 19 Operators and Abstraction Announcements Reading Tuesday: Chapter 18 Thursday reading online Assignments A4 due tonight at Midnight 10 pts per day late Consultants available tonight A5 posted

More information

S206E Lecture 21, 5/26/2016, Python classes

S206E Lecture 21, 5/26/2016, Python classes S206E057 Spring 2016 Copyright 2016, Chiu-Shui Chan. All Rights Reserved. Python has the notions of classes and objects from using dictionaries and modules to facilitate repetitious tasks. Information

More information

BASIC CONCEPT OF OOP

BASIC CONCEPT OF OOP Chapter-6 BASIC CONCEPT OF OOP Introduction: Object oriented programmingg is the principle of design and development of programs using modular approach. Object oriented programmingg approach provides advantages

More information

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19 1 Classes 2 Exceptions 3 Using Other Code 4 Problems Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, 2009 1 / 19 Start with an Example Python is object oriented Everything is an object

More information

61A Lecture 2. Wednesday, September 4, 2013

61A Lecture 2. Wednesday, September 4, 2013 61A Lecture 2 Wednesday, September 4, 2013 Names, Assignment, and User-Defined Functions (Demo) Types of Expressions Primitive expressions: 2 add 'hello' Number or Numeral Name String Call expressions:

More information

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi

Modern C++ for Computer Vision and Image Processing. Igor Bogoslavskyi Modern C++ for Computer Vision and Image Processing Igor Bogoslavskyi Outline Move semantics Classes Operator overloading Making your class copyable Making your class movable Rule of all or nothing Inheritance

More information

CMSC 132: Object-Oriented Programming II

CMSC 132: Object-Oriented Programming II CMSC 132: Object-Oriented Programming II Java Support for OOP Department of Computer Science University of Maryland, College Park Object Oriented Programming (OOP) OO Principles Abstraction Encapsulation

More information

1. Write two major differences between Object-oriented programming and procedural programming?

1. Write two major differences between Object-oriented programming and procedural programming? 1. Write two major differences between Object-oriented programming and procedural programming? A procedural program is written as a list of instructions, telling the computer, step-by-step, what to do:

More information

Write for your audience

Write for your audience Comments Write for your audience Program documentation is for programmers, not end users There are two groups of programmers, and they need different kinds of documentation Some programmers need to use

More information

1: Introduction to Object (1)

1: Introduction to Object (1) 1: Introduction to Object (1) 김동원 2003.01.20 Overview (1) The progress of abstraction Smalltalk Class & Object Interface The hidden implementation Reusing the implementation Inheritance: Reusing the interface

More information

Fundamentals of Programming. Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014

Fundamentals of Programming. Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014 15-112 Fundamentals of Programming Functions Redux. Event-based Programming. File and Web IO. November 4th, 2014 Today Briefly show file and web IO. Revisit functions. Learn a bit more about them. Event-based

More information

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Introduction Robert Rand University of Pennsylvania September 16, 2015 Robert Rand (University of Pennsylvania) CIS 192 September 16, 2015 1 / 21 Outline 1 Object Orientation

More information

C++ Important Questions with Answers

C++ Important Questions with Answers 1. Name the operators that cannot be overloaded. sizeof,.,.*,.->, ::,? 2. What is inheritance? Inheritance is property such that a parent (or super) class passes the characteristics of itself to children

More information

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT

CSCI 204 Introduction to Computer Science II. Lab 6: Stack ADT CSCI 204 Introduction to Computer Science II 1. Objectives In this lab, you will practice the following: Learn about the Stack ADT Implement the Stack ADT using an array Lab 6: Stack ADT Use a Stack to

More information

Final thoughts on functions F E B 2 5 T H

Final thoughts on functions F E B 2 5 T H Final thoughts on functions F E B 2 5 T H Ordering functions in your code Will the following code work? Here the function is defined after the main program that is calling it. print foo() def foo(): return

More information

Announcements for this Lecture

Announcements for this Lecture Lecture 6 Objects Announcements for this Lecture Last Call Quiz: About the Course Take it by tomorrow Also remember survey Assignment 1 Assignment 1 is live Posted on web page Due Thur, Sep. 18 th Due

More information

A Crash Course in Python Part II. Presented by Cuauhtémoc Carbajal ITESM CEM

A Crash Course in Python Part II. Presented by Cuauhtémoc Carbajal ITESM CEM A Crash Course in Python Part II Presented by Cuauhtémoc Carbajal ITESM CEM 1 Importing and Modules 2 Importing and Modules Use classes & functions defined in another file A Python module is a file with

More information

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity. OOPS Viva Questions 1. What is OOPS? OOPS is abbreviated as Object Oriented Programming system in which programs are considered as a collection of objects. Each object is nothing but an instance of a class.

More information

AN OVERVIEW OF C++ 1

AN OVERVIEW OF C++ 1 AN OVERVIEW OF C++ 1 OBJECTIVES Introduction What is object-oriented programming? Two versions of C++ C++ console I/O C++ comments Classes: A first look Some differences between C and C++ Introducing function

More information

Introduction to Object-Oriented Programming

Introduction to Object-Oriented Programming Introduction to Python Programming Introduction to Object-Oriented Programming Annemarie Friedrich (anne@cis.uni-muenchen.de) Centrum für Informations- und Sprachverarbeitung LMU München Software objects

More information

OBJECT ORIENTED PROGRAMMING

OBJECT ORIENTED PROGRAMMING OBJECT ORIENTED PROGRAMMING (download slides and.py files follow along!) 6.0001 LECTURE 8 6.0001 LECTURE 8 1 OBJECTS Python supports many different kinds of data 1234 3.14159 "Hello" [1, 5, 7, 11, 13]

More information

12. Pointers Address-of operator (&)

12. Pointers Address-of operator (&) 12. Pointers In earlier chapters, variables have been explained as locations in the computer's memory which can be accessed by their identifer (their name). This way, the program does not need to care

More information

4. Write sets of directions for how to check for direct variation. How to check for direct variation by analyzing the graph :

4. Write sets of directions for how to check for direct variation. How to check for direct variation by analyzing the graph : Name Direct Variations There are many relationships that two variables can have. One of these relationships is called a direct variation. Use the description and example of direct variation to help you

More information