COMP519 Web Programming Lecture 21: Python (Part 5) Handouts

Size: px
Start display at page:

Download "COMP519 Web Programming Lecture 21: Python (Part 5) Handouts"

Transcription

1 COMP519 Web Programming Lecture 21: Python (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

2 Functions Classes Revision Contents 1 Functions Variable Scope and Functions Static Variables 2 Classes Defining and Instantiating a Class Class and Instance Attributes Deleting Instances Class Methods Inheritance Magic Methods 3 Further Reading Ullrich Hustadt COMP519 Web Programming L21 1

3 Functions Classes Revision Variable Scope and Functions Static vars Scope of Variables Sope of a Variable (Occurrence) The region of a program or the sequence of execution steps of a program in which we can validly refer to that variable (occurrence) public class Test { int x; void method1 () {... A... int x; int y;... B... } void method2 () {... C... } int z; } Where in this Java class can we validly refer to the variables x, y and z, for example, print them out? Can we refer to x, y, and z in method2()? Which occurrence of x do we refer to? Which occurrence of x would we refer to in method1() either in section...a... or...b...? Such questions become even more complicated when function definitions can be nested as in JavaScript and Python Ullrich Hustadt COMP519 Web Programming L21 2

4 Functions Classes Revision Variable Scope and Functions Static vars A Look Back to JavaScript function state (s,a,k,b,l,c,m) { document. writeln (s+ : +a+ = +k+, + b+ = +l+, +c+ =[ +m+ ]<br /> ) } function outer (x,y,z) { function inner () { state ( Inner (1), x,x, y,y, z,z) x = 3 z [1] = 3 state ( Inner (2), x,x, y,y, z,z) } state ( Outer (1), x,x, y,y, z,z) inner () y = 4 z [2] = 4 state ( Outer (2), x,x, y,y, z,z) } u = 1; v = 2; w = [0,1,2] state ( Main (1), u,u, v,v, w,w) outer (u,v,w) state ( Main (2), u,u, v,v, w,w) Main(1): u=1, v=2, w=[0,1,2] Outer(1): x=1, y=2, z=[0,1,2] Inner(1): x=1, y=2, z=[0,1,2] Inner(2): x=3, y=2, z=[0,3,2] Outer(2): x=3, y=4, z=[0,3,4] Main(2): u=1, v=2, w=[0,3,4] x, y, z are local variables of outer x, y, z in inner are those of outer x, y, z are accessible in inner Ullrich Hustadt COMP519 Web Programming L21 3

5 Functions Classes Revision Variable Scope and Functions Static vars Variable Scope in Python: Example def state (s,a,k,b,l,c,m): print (s+ : +a+ = + str (k)+, + b+ = + str (l)+, +c+ = + str (m)) def outer (x,y,z): def inner (): state ( Inner (1), x,x, y,y, z,z) x = 3 z [1] = 3 state ( Inner (2), x,x, y,y, z,z) state ( Outer (1), x,x, y,y, z,z) inner () y = 4 z [2] = 4 state ( Outer (2), x,x, y,y, z,z) u, v, w = 1, 2, [0,1,2] state ( Main (1), u,u, v,v, w,w) outer (u,v,w) state ( Main (2), u,u, v,v, w,w) Main(1): u=1, v=2, w=[0,1,2] Outer(1): x=1, y=2, z=[0,1,2] Traceback (most recent call last): line 20, in <module> outer(u,v,w) line 13, in outer inner() line 8, in inner state( Inner(1), x,x, y,...) UnboundLocalError: local variable x referenced before assignment x in inner is a local variabe of inner x in inner is not the same as x in outer y in inner is the same as y in outer z in inner is the same as z in outer Ullrich Hustadt COMP519 Web Programming L21 4

6 Functions Classes Revision Variable Scope and Functions Static vars Variable Scope in Python: Analysis By default, any assignment to a variable within a function creates a new local variable def outer (x,y,z): def inner (): x = 3 # x is a new local variable Not all statements that look like assignments are assignments def bubble_sort ( arr ): def swap (i, j): arr [ i] = tmp # why is arr not a new local variable? is syntactic sugar for def bubble_sort ( arr ): def swap (i, j): arr. setitem (i,tmp ) that is, the assignment is a method call for the object arr arr[i] = tmp does not result in the creation of a new local variable arr Ullrich Hustadt COMP519 Web Programming L21 5

7 Functions Classes Revision Variable Scope and Functions Static vars Variable Scope in Python A variable that is a function parameter or defined inside a function is local to that function the variable (only) exists as long as a function execution does the variable can only be accessed inside the function A variable that is outside any function (or class) is global the variable can be accessed anywhere if is not hidden by a local variable with the same name The declaration global var1, var2,... causes the listed variables to be interpreted as global variables The declaration nonlocal var1, var2,... causes the listed variables to refer to previously bound variables in the nearest enclosing scope excluding globals Ullrich Hustadt COMP519 Web Programming L21 6

8 Functions Classes Revision Variable Scope and Functions Static vars Global vs Local Variables in Python def state (s,a,k,b,l,c,m): print (s+ : +a+ = + str (k)+, + b+ = + str (l)+, +c+ = + str (m)) def outer (x,y,z): def inner (): nonlocal x state ( Inner (1), x,x, y,y, z,z) x = 3 z [1] = 3 state ( Inner (2), x,x, y,y, z,z) state ( Outer (1), x,x, y,y, z,z) inner () y = 4 z [2] = 4 state ( Outer (2), x,x, y,y, z,z) u, v, w = 1, 2, [0,1,2] state ( Main (1), u,u, v,v, w,w) outer (u,v,w) state ( Main (2), u,u, v,v, w,w) Main(1): u=1, v=2, w=[0,1,2] Outer(1): x=1, y=2, z=[0,1,2] Inner(1): x=1, y=2, z=[0,1,2] Inner(2): x=3, y=2, z=[0, 3, 2] Outer(2): x=3, y=4, z=[0, 3, 4] Main(2): u=1, v=2, w=[0, 3, 4] x in inner is now the same as x in outer y in inner is the same as y in outer z in inner is the same as z in outer Ullrich Hustadt COMP519 Web Programming L21 7

9 Functions Classes Revision Variable Scope and Functions Static vars Python Functions and Static Variables Python does not have a ^Astatic^A keyword to declare a variable to be static and preserve its value between different calls of a function The solution is to use a function attribute instead def counter (): try : counter. count += 1 except AttributeError : counter. count = 1 return counter. count print ("1: static count =", counter ()) print ("2: static count =", counter ()) print ("3: global counter. count = "+ counter. count ) 1: static count = 1 2: static count = 2 3: global counter. count = 2 As the example shows the function attribute is global/public Ullrich Hustadt COMP519 Web Programming L21 8

10 Functions Classes Revision Variable Scope and Functions Static vars Anonymous Functions Python supports a weak form of anonymous functions: lambda param1, param2,...: expression Parameters work as for named functions The return value of an anonymous function is the value of expression lambda x, y: x**y if y > 0 else x **(1/ y) Both named and anonymous functions can be assigned to variables: def exp (base, exp ): return base ** exp func1 = exp func2 = lambda x: 2* x print ( func1 (2,2) + func2 (3)) # prints 10 Both named and anonymous functions can be passed to other functions as arguments or used as values in complex data structures Ullrich Hustadt COMP519 Web Programming L21 9

11 Defining and Instantiating a Class Python is an object-oriented language with classes A class can be defined as follows: class identifier : docstring suite The class name identifier is case-sensitive docstring is a string describing the class and will be returned by help(identifier) or identifier. doc suite is a non-empty sequence of statements, typically defining attributes and methods An object of a class is created using identifier (arg1,arg2,...) where arg1,arg2,... is a possibly empty list of arguments passed to the constructor of the class identifier Ullrich Hustadt COMP519 Web Programming L21 10

12 A Closer Look at Class Definitions In more detail, the definition of a class typically looks as follows class id: docstring # Class Attributes cattrib = value1 # Constructor def init (self,p1,p2,...): # Instance Attribute self. iattrib = value2 suite1 # Methods def method2 (self,p1,p2,...): suite2 def methodn (self,p1,p2,...): suiten Every instance obj of this class will have an attribute iattrib accessible as obj.iattrib cattrib is a class attribute accessible as id.cattrib or obj.cattrib init is the constructor of the class and will be called whenever id(a1,a2,...) is executed Via self the constructor receives a reference to the newly created object p1,p2,... will be instantiated by a1,a2,... Ullrich Hustadt COMP519 Web Programming L21 11

13 A Closer Look at Class Definitions In more detail, the definition of a class typically looks as follows class id: docstring # Class Attributes cattrib = value1 # Constructor def init (self,p1,p2,...): # Instance Attribute self. iattrib = value2 suite1 # Methods def method2 (self,p1,p2,...): suite2 def methodn (self,p1,p2,...): suiten Every instance obj of this class will have methods method2 to methodn For an instance obj of this class, method calls will take the form obj.method2(a1,a2,...) to obj.methodn(a1,a2,...) p1,p2,... will be instantiated by a1,a2,... in the normal way for function calls Via self each method receives a reference to obj as additional argument Ullrich Hustadt COMP519 Web Programming L21 12

14 Defining and Instantiating a Class: Example class Rectangle : """ A simple rectangle class """ type = Rectangle def init (self, width =0, height =0): self. width = width self. height = height def area ( self ): return self. height * self. width # Using the class r1 = Rectangle () print ( Area of r1:,r1. area ()) r2 = Rectangle (5,2) print ( Area of r2:,r2. area ()) r3 = Rectangle ( width =5, height =2) print ( Area of r3:,r3. area ()) Area of r1: 0 Area of r2: 10 Area of r3: 10 Ullrich Hustadt COMP519 Web Programming L21 13

15 Class and Instance Attributes Class attributes are owned by the class itself and shared by all instances of the class Instance attributes are owned by the specific instances of a class Instances can be given additional attributes (and methods) at any time Assigning a value to a class attribute via an instance creates a new instance variable For an instance obj, obj. dict returns a dictionary of all instance variable and their values of obj print (" Dictionary : ",r2. dict," Type :", r2. type ) Dictionary : { width : 5, height : 2} Type : Rectangle r1. colour = " blue " r1. type = " Point " print (r1. dict ) { width : 0, height : 0, colour : blue, type : Point } Ullrich Hustadt COMP519 Web Programming L21 14

16 Private Attributes Python has no private class or instance attributes By convention, attributes whose name starts with a double underscore should be considered private Python supports this convention by name mangling: Within the definition of a class id an attribute attrib is textually replaced by _id attrib class Hide : chide = 1 def init ( self ): self. ihide = 2 h1 = Hide () print (" Class : ", Hide. dict ) print (" Instance :", h1. dict ) print (" Value of ihide for h1 :", h1. _Hide ihide ) print (h1. ihide ) Class : { _Hide chide : 1, init :... } Instance : { _Hide ihide : 2} Value of ihide for h1: 2 AttributeError : Hide object has no attribute ihide Ullrich Hustadt COMP519 Web Programming L21 15

17 Private Attributes: Example class Mapping : def init (self, iterable ): self. items_ list = [] self. update ( iterable ) def update ( self, iterable ): for item in iterable : self. items_list. append ( item ) update = update # private copy of original update () class MappingSubclass ( Mapping ): def update ( self, keys, values ): # provides a new signature and definition for update () # but does not break init () in Mapping for item in zip ( keys, values ): self. items_list. append ( item ) Section 9.6. Private Variables ( of Python Software Foundation: The Python Tutorial. Python Software Foundation, 21 December [accessed 21 December 2017] Ullrich Hustadt COMP519 Web Programming L21 16

18 Deleting Instances An instance obj can be deleted using del obj Deleting an instance will implicitly call the method del class Employee : totalnumber = 0; def init (self, name ): self. name = name type ( self ). totalnumber += 1 def del ( self ): type ( self ). totalnumber -= 1 A: # employees : 2 B: # employees : 1 C: # employees : 0 e1 = Employee (" Ada ") e2 = Employee (" Ben ") print ("A: # employees : ", Employee. totalnumber ) del e1 print ("B: # employees : ", Employee. totalnumber ) e2 = None print ("C: # employees : ", Employee. totalnumber ) Ullrich Hustadt COMP519 Web Programming L21 17

19 Static Methods (Class Methods) The Pythonic way is to define getter and setter method only for private class and instance attributes For private instance variables this is done in the standard way For private class variables we need to declare the getter / setter method to be static e3 = Employee (" Ada ") e4 = Employee (" Ben ") print (" Number of employees : ", Employee. getnumber ()) print (" Number of employees : ", e3. getnumber ()) Number of employees : 2 Number of employees : 2 class Employee : tnum = 0; def init (self, name ): self. name = name type ( self ). tnum += 1 def del ( self ): type ( self ). tnum -= 1 def getname ( self ): return self. name def setname (self, name ): self. name = staticmethod def getnumber (): return Employee. tnum Ullrich Hustadt COMP519 Web Programming L21 18

20 Static Methods (Class Methods) A static declaration should also be used for methods that are independant of specific instances class Circle : PI = c1 = Circle (1.2) c2 = Circle (1.0) def init (self, radius ): self. r = radius def area ( self ): return round ( Circle. PI * \ self.r * staticmethod def max (cx,cy ): if cx.r > cy.r: return cx else : return cy print (" c1 radius :", c1.r) print (" c1 area : ",c1. area ()) print (" c2 radius :", c2.r) print (" c2 area : ",c2. area ()) bg = Circle. max (c1,c2) print (" bg radius :", bg.r) c1 radius : 1.2 c1 area : c2 radius : 1.0 c2 area : bg radius : 1.2 Ullrich Hustadt COMP519 Web Programming L21 19

21 Inheritance In a class definition it is possible to specify one or more superclasses from which a class should inherit attributes and methods: class identifier ( Super1, Super2,...): docstring suite class Rectangle : """ A simple rectangle class """ type = Rectangle def init (self, width =0, height =0): self. width = width self. height = height def area ( self ): return self. height * self. width class Square ( Rectangle ): type = Square def init (self, size ): super (). init (size, size ) sq1 = Square (5) print (" The type of sq1 is", sq1. type ) print (" The area of sq1 is", sq1. area () ) The type of sq1 is Square The area of sq1 is 25 Ullrich Hustadt COMP519 Web Programming L21 20

22 Magic Methods init and del are examples of magic methods: Methods that are invoked when a certain language constructs is used or a particular condition becomes true Other examples include: getitem setitem str allows instances to use the [] (indexer) operators to get or set a value called by str(), print(), format() to obtain a string representation of an instance eq called by comparison operator == lt called by comparison operator < add called by binary operator + bool called for truth value testing and by bool(), should return True or False iter called by for-loop to iterate over the elements next of an iterable object Ullrich Hustadt COMP519 Web Programming L21 21

23 Magic Methods: Index Operators A class implementing getitem (self,key) setitem (self,key,value) allows instances to use the [] operator to access values class Building : def init (self, floors ): self. floors = [ None ]* floors def setitem (self, floor_number, data ): self. floors [ floor_number ] = data def getitem (self, floor_number ): return self. floors [ floor_number ] building1 = Building (3) building1 [0] = Reception building1 [1] = ABC Corp building1 [2] = DEF Ltd print ( building1 [2] ) # prints DEF Ltd Ullrich Hustadt COMP519 Web Programming L21 22

24 Magic Methods: Iterators A for-loop starts by calling the iter () on an object to obtain an iterator object At each iteration (including the first), a for-loop calls the next () method on the iterator object to get the next item If next () raises the exception StopIteration, the for-loop stops class PowTwo : def init (self, max = 0): self. max = max def iter ( self ): self.n = 0 return self def next ( self ): if self.n <= self. max : result = 2 ** self. n self.n += 1 return result else : raise StopIteration for x in PowTwo (2): print (x) 1 # 2 ** 0 2 # 2 ** 1 4 # 2 ** 2 Ullrich Hustadt COMP519 Web Programming L21 23

25 Functions Classes Revision Revision and Further Reading Read Section 9: Classes ( of Python Software Foundation: The Python Tutorial. Python Software Foundation, 21 December [accessed 21 December 2017] Read Chapter: Object-Oriented Programming ( eu/python3_object_oriented_programming.php) and all remaining chapters of Bernd Klein: Python 3 Tutorial. bodenseo Python Training Couses, 21 December [accessed 21 December 2017] Ullrich Hustadt COMP519 Web Programming L21 24

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts COMP519 Web Programming Lecture 20: Python (Part 4) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts

COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts COMP519 Web Programming Lecture 14: JavaScript (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

COMP284 Scripting Languages Lecture 13: PHP (Part 5) Handouts

COMP284 Scripting Languages Lecture 13: PHP (Part 5) Handouts COMP284 Scripting Languages Lecture 13: PHP (Part 5) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts

COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts COMP519 Web Programming Lecture 27: PHP (Part 3) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Control

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

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

Lessons on Python Classes and Objects

Lessons on Python Classes and Objects Lessons on Python Classes and Objects Walter Didimo [ 120 minutes ] Outline We will introduce basic concepts about classes and objects in Python a comprehensive lesson on this topic would require much

More information

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts

COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts COMP519 Web Programming Lecture 11: JavaScript (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

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

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object-Oriented Programming Robert Rand University of Pennsylvania February 10, 2016 Robert Rand (University of Pennsylvania) CIS 192 February 10, 2016 1 / 25 Outline 1 Object

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

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts

COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts COMP284 Scripting Languages Lecture 11: PHP (Part 3) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1

Lecture #15: Generic Functions and Expressivity. Last modified: Wed Mar 1 15:51: CS61A: Lecture #16 1 Lecture #15: Generic Functions and Expressivity Last modified: Wed Mar 1 15:51:48 2017 CS61A: Lecture #16 1 Consider the function find: Generic Programming def find(l, x, k): """Return the index in L of

More information

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

More information

CSC148 Intro. to Computer Science

CSC148 Intro. to Computer Science CSC148 Intro. to Computer Science Lecture 2: designing classes, special methods, managing attributes; intro composition, inheritance Amir H. Chinaei, Summer 2016 Office Hours: R 10 12 BA4222 csc148ta@cdf.toronto.edu

More information

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers

Lecture 27. Lecture 27: Regular Expressions and Python Identifiers Lecture 27 Lecture 27: Regular Expressions and Python Identifiers Python Syntax Python syntax makes very few restrictions on the ways that we can name our variables, functions, and classes. Variables names

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Functional Programming Eric Kutschera University of Pennsylvania January 30, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 January 30, 2015 1 / 31 Questions Homework

More information

JavaScript: Sort of a Big Deal,

JavaScript: Sort of a Big Deal, : Sort of a Big Deal, But Sort of Quirky... March 20, 2017 Lisp in C s Clothing (Crockford, 2001) Dynamically Typed: no static type annotations or type checks. C-Like Syntax: curly-braces, for, semicolons,

More information

Babu Madhav Institute of Information Technology, UTU 2015

Babu Madhav Institute of Information Technology, UTU 2015 Five years Integrated M.Sc.(IT)(Semester 5) Question Bank 060010502:Programming in Python Unit-1:Introduction To Python Q-1 Answer the following Questions in short. 1. Which operator is used for slicing?

More information

Object Orientation Fourth Story. Bok, Jong Soon

Object Orientation Fourth Story. Bok, Jong Soon Object Orientation Fourth Story Bok, Jong Soon javaexpert@nate.com www.javaexpert.co.kr abstract Methods Java allows you to specify that a superclass declares a method that does not supply an implementation.

More information

The Pyth Language. Administrivia

The Pyth Language. Administrivia Administrivia The Pyth Language Lecture 5 Please make sure you have registered your team, created SSH keys as indicated on the admin page, and also have electronically registered with us as well. Prof.

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

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

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

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts

COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts COMP284 Scripting Languages Lecture 15: JavaScript (Part 2) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

Functional Programming and Haskell

Functional Programming and Haskell Functional Programming and Haskell Tim Dawborn University of Sydney, Australia School of Information Technologies Tim Dawborn Functional Programming and Haskell 1/22 What are Programming Paradigms? A programming

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

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99 1. A function is a procedural abstract (a named body of code to perform some action and return a resulting value). The syntax of a function definition is: def functionname([parameter [, parameter]*]):

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Object Oriented Programming Harry Smith University of Pennsylvania February 15, 2016 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2016 1 / 26 Outline

More information

Introduction to Python programming, II

Introduction to Python programming, II Grid Computing Competence Center Introduction to Python programming, II Riccardo Murri Grid Computing Competence Center, Organisch-Chemisches Institut, University of Zurich Nov. 16, 2011 Today s class

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

Algorithms and Programming

Algorithms and Programming Algorithms and Programming Lecture 6 Classes, UML, NumPy Camelia Chira Course content Introduction in the software development process Procedural programming Modular programming Abstract data types Software

More information

At full speed with Python

At full speed with Python At full speed with Python João Ventura v0.1 Contents 1 Introduction 2 2 Installation 3 2.1 Installing on Windows............................ 3 2.2 Installing on macos............................. 5 2.3

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

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

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

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed CREATED BY: Muhammad Bilal Arslan Ahmad Shaad JAVA Chapter No 5 Instructor: Muhammad Naveed Muhammad Bilal Arslan Ahmad Shaad Chapter No 5 Object Oriented Programming Q: Explain subclass and inheritance?

More information

COMP 401 Spring 2013 Midterm 1

COMP 401 Spring 2013 Midterm 1 COMP 401 Spring 2013 Midterm 1 I have not received nor given any unauthorized assistance in completing this exam. Signature: Name: PID: Please be sure to put your PID at the top of each page. This page

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

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 20, 2014 Abstract

More information

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון Classes and Methods לאוניד ברנבוים המחלקה למדעי המחשב אוניברסיטת בן-גוריון 22 Roadmap Lectures 4 and 5 present two sides of OOP: Lecture 4 discusses the static, compile time representation of object-oriented

More information

SML A F unctional Functional Language Language Lecture 19

SML A F unctional Functional Language Language Lecture 19 SML A Functional Language Lecture 19 Introduction to SML SML is a functional programming language and acronym for Standard d Meta Language. SML has basic data objects as expressions, functions and list

More information

INF3110 Programming Languages Runtime Organization part II

INF3110 Programming Languages Runtime Organization part II INF3110 Programming Languages Runtime Organization part II 10/24/17 1 Today: Higher-Order Functions, and Objects at runtime Higher-order functions: Functions passed as arguments Functions that return functions

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, IO, and Exceptions Harry Smith University of Pennsylvania February 15, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 5 February 15, 2018

More information

Assignment 7: functions and closure conversion (part 1)

Assignment 7: functions and closure conversion (part 1) Assignment 7: functions and closure conversion (part 1) ECEN 4553 & 5013, CSCI 4555 & 5525 Prof. Jeremy G. Siek November 12, 2008 The main ideas for this week are: first-class functions lexical scoping

More information

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell

Haske k ll An introduction to Functional functional programming using Haskell Purely Lazy Example: QuickSort in Java Example: QuickSort in Haskell Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dk The most popular purely functional, lazy programming language Functional programming language : a program

More information

Lecture 2: Java & Javadoc

Lecture 2: Java & Javadoc Lecture 2: Java & Javadoc CS 62 Fall 2018 Alexandra Papoutsaki & William Devanny 1 Instance Variables or member variables or fields Declared in a class, but outside of any method, constructor or block

More information

Ruby: Introduction, Basics

Ruby: Introduction, Basics Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie

More information

CIS192: Python Programming

CIS192: Python Programming CIS192: Python Programming Functions and Functional Programming Harry Smith University of Pennsylvania January 25, 2018 Harry Smith (University of Pennsylvania) CIS 192 Lecture 3 January 25, 2018 1 / 39

More information

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.) CHAPTER 5 Functions The main ideas in this chapter are: first-class functions: functions are values that can be passed as arguments to other functions, returned from functions, stored in lists and dictionaries,

More information

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM

CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM CS100J, Fall 2003 Preparing for Prelim 1: Monday, 29 Sept., 7:30 9:00PM This handout explains what you have to know for the first prelim. Terms and their meaning Below, we summarize the terms you should

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Iterators, Generators, Exceptions & IO Raymond Yin University of Pennsylvania September 28, 2016 Raymond Yin (University of Pennsylvania) CIS 192 September 28, 2016 1 / 26 Outline

More information

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts

COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts COMP284 Scripting Languages Lecture 14: JavaScript (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool

More information

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts

COMP519 Web Programming Lecture 17: Python (Part 1) Handouts COMP519 Web Programming Lecture 17: Python (Part 1) Handouts Ullrich Hustadt Department of Computer Science School of Electrical Engineering, Electronics, and Computer Science University of Liverpool Contents

More information

ITI Introduction to Computing II

ITI Introduction to Computing II ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Inheritance Introduction Generalization/specialization Version of January 21, 2013 Abstract

More information

An introduction introduction to functional functional programming programming using usin Haskell

An introduction introduction to functional functional programming programming using usin Haskell An introduction to functional programming using Haskell Anders Møller amoeller@cs.au.dkau Haskell The most popular p purely functional, lazy programming g language Functional programming language : a program

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

G Programming Languages - Fall 2012

G Programming Languages - Fall 2012 G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing

More information

CS-202 Introduction to Object Oriented Programming

CS-202 Introduction to Object Oriented Programming CS-202 Introduction to Object Oriented Programming California State University, Los Angeles Computer Science Department Lecture III Inheritance and Polymorphism Introduction to Inheritance Introduction

More information

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples

Introduction to Typed Racket. The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Introduction to Typed Racket The plan: Racket Crash Course Typed Racket and PL Racket Differences with the text Some PL Racket Examples Getting started Find a machine with DrRacket installed (e.g. the

More information

Reminder About Functions

Reminder About Functions Reminder About Functions (let ((z 17)) (let ((z 3) (a ) (x (lambda (x y) (- x (+ y z))))) (let ((z 0) (a )) (x z a)))) int h, i; void B(int w) { int j, k; i = 2*w; w = w+1; void A(int x, int y) { bool

More information

Comments are almost like C++

Comments are almost like C++ UMBC CMSC 331 Java Comments are almost like C++ The javadoc program generates HTML API documentation from the javadoc style comments in your code. /* This kind of comment can span multiple lines */ //

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Generators Exceptions and IO Eric Kutschera University of Pennsylvania February 13, 2015 Eric Kutschera (University of Pennsylvania) CIS 192 February 13, 2015 1 / 24 Outline 1

More information

Types and Type Inference

Types and Type Inference CS 242 2012 Types and Type Inference Notes modified from John Mitchell and Kathleen Fisher Reading: Concepts in Programming Languages, Revised Chapter 6 - handout on Web!! Outline General discussion of

More information

Java: introduction to object-oriented features

Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer Java: introduction to object-oriented features Chair of Software Engineering Carlo A. Furia, Marco Piccioni, Bertrand Meyer

More information

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming Overview of OOP Object Oriented Programming is a programming method that combines: a) Data b) Instructions for processing that data into a self-sufficient object that can be used within a program or in

More information

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science

Recall. Key terms. Review. Encapsulation (by getters, setters, properties) OOP Features. CSC148 Intro. to Computer Science CSC148 Intro. to Computer Science Lecture 3: designing classes, special methods, composition, inheritance, Stack, Sack Amir H. Chinaei, Summer 2016 Office Hours: R 10-12 BA4222 ahchinaei@cs.toronto.edu

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

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1

Lecture #16: Generic Functions and Expressivity. Last modified: Fri Feb 26 19:16: CS61A: Lecture #16 1 Lecture #16: Generic Functions and Expressivity Last modified: Fri Feb 26 19:16:38 2016 CS61A: Lecture #16 1 Consider the function find: Generic Programming def find(l, x, k): """Return the index in L

More information

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות

Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות Classes and Methods עזאם מרעי המחלקה למדעי המחשב אוניברסיטת בן-גוריון מבוסס על השקפים של אותו קורס שניתן בשנים הקודמות 2 Roadmap Lectures 4 and 5 present two sides of OOP: Lecture 4 discusses the static,

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

CSE 3302 Programming Languages Lecture 8: Functional Programming

CSE 3302 Programming Languages Lecture 8: Functional Programming CSE 3302 Programming Languages Lecture 8: Functional Programming (based on the slides by Tim Sheard) Leonidas Fegaras University of Texas at Arlington CSE 3302 L8 Spring 2011 1 Functional Programming Languages

More information

Inheritance and Interfaces

Inheritance and Interfaces Inheritance and Interfaces Object Orientated Programming in Java Benjamin Kenwright Outline Review What is Inheritance? Why we need Inheritance? Syntax, Formatting,.. What is an Interface? Today s Practical

More information

CPS 506 Comparative Programming Languages. Programming Language

CPS 506 Comparative Programming Languages. Programming Language CPS 506 Comparative Programming Languages Object-Oriented Oriented Programming Language Paradigm Introduction Topics Object-Oriented Programming Design Issues for Object-Oriented Oriented Languages Support

More information

1 Shyam sir JAVA Notes

1 Shyam sir JAVA Notes 1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write

More information

Chapter 5. Names, Bindings, and Scopes

Chapter 5. Names, Bindings, and Scopes Chapter 5 Names, Bindings, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Scope Scope and Lifetime Referencing Environments Named Constants 1-2 Introduction Imperative

More information

CSC148 Recipe for Designing Classes

CSC148 Recipe for Designing Classes Part 1: Define the API for the class CSC148 Recipe for Designing Classes Download the sample code here: https://www.teach.cs.toronto.edu/~csc148h/fall/lectures/object-oriented-programming/common/course.

More information

Chapter 1. Fundamentals of Higher Order Programming

Chapter 1. Fundamentals of Higher Order Programming Chapter 1 Fundamentals of Higher Order Programming 1 The Elements of Programming Any powerful language features: so does Scheme primitive data procedures combinations abstraction We will see that Scheme

More information

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון

Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון Classes and Methods גרא וייס המחלקה למדעי המחשב אוניברסיטת בן-גוריון 2 Roadmap Lectures 4 and 5 present two sides of OOP: Lecture 4 discusses the static, compile time representation of object-oriented

More information

Topic 7: Algebraic Data Types

Topic 7: Algebraic Data Types Topic 7: Algebraic Data Types 1 Recommended Exercises and Readings From Haskell: The craft of functional programming (3 rd Ed.) Exercises: 5.5, 5.7, 5.8, 5.10, 5.11, 5.12, 5.14 14.4, 14.5, 14.6 14.9, 14.11,

More information

COMP-520 GoLite Tutorial

COMP-520 GoLite Tutorial COMP-520 GoLite Tutorial Alexander Krolik Sable Lab McGill University Winter 2019 Plan Target languages Language constructs, emphasis on special cases General execution semantics Declarations Types Statements

More information

LECTURE 6. Advanced Functions and OOP

LECTURE 6. Advanced Functions and OOP LECTURE 6 Advanced Functions and OOP FUNCTIONS Before we start, let s talk about how name resolution is done in Python: When a function executes, a new namespace is created (locals). New namespaces can

More information

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009

Python A Technical Introduction. James Heliotis Rochester Institute of Technology December, 2009 Python A Technical Introduction James Heliotis Rochester Institute of Technology December, 2009 Background & Overview Beginnings Developed by Guido Van Rossum, BDFL, in 1990 (Guido is a Monty Python fan.)

More information

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;

More information

CS 360: Programming Languages Lecture 12: More Haskell

CS 360: Programming Languages Lecture 12: More Haskell CS 360: Programming Languages Lecture 12: More Haskell Geoffrey Mainland Drexel University Adapted from Brent Yorgey s course Introduction to Haskell. Section 1 Administrivia Administrivia Homework 5 due

More information

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.)

Functions CHAPTER 5. FIGURE 1. Concrete syntax for the P 2 subset of Python. (In addition to that of P 1.) CHAPTER 5 Functions The main ideas in this chapter are: first-class functions: functions are values that can be passed as arguments to other functions, returned from functions, stored in lists and dictionaries,

More information

Programming overview

Programming overview Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in

More information

CSCI312 Principles of Programming Languages!

CSCI312 Principles of Programming Languages! CSCI312 Principles of Programming Languages! Scope Xu Liu ! 4.1 Syntactic Issues! 4.2 Variables! 4.3 Scope! 4.4 Symbol Table! 4.5 Resolving References! 4.6 Dynamic Scoping! 4.7 Visibility! 4.8 Overloading!

More information

Variable and Data Type I

Variable and Data Type I Islamic University Of Gaza Faculty of Engineering Computer Engineering Department Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad September 24, 2016 Variable is reserved a location in memory to store

More information

Test 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B.

Test 1 Summer 2014 Multiple Choice. Write your answer to the LEFT of each problem. 5 points each 1. Preprocessor macros are associated with: A. C B. CSE 3302 Test 1 1. Preprocessor macros are associated with: A. C B. Java C. JavaScript D. Pascal 2. (define x (lambda (y z) (+ y z))) is an example of: A. Applying an anonymous function B. Defining a function

More information

Scope and Parameter Passing 1 / 19

Scope and Parameter Passing 1 / 19 Scope and Parameter Passing 1 / 19 Outline Overview Naming and scope Function/procedure calls Static vs. dynamic scope Parameter passing schemes 2 / 19 Review of naming Most languages provide a way to

More information

Mobile Application Programming. Swift Classes

Mobile Application Programming. Swift Classes Mobile Application Programming Swift Classes Swift Top-Level Entities Like C/C++ but unlike Java, Swift allows declarations of functions, variables, and constants at the top-level, outside any class declaration

More information

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections)

Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections) CS 61A Structure and Interpretation of Computer Programs Spring 2014 Final (with corrections) INSTRUCTIONS You have 3 hours to complete the exam. The exam is open book and open notes. You may not use a

More information

A Short Summary of Javali

A Short Summary of Javali A Short Summary of Javali October 15, 2015 1 Introduction Javali is a simple language based on ideas found in languages like C++ or Java. Its purpose is to serve as the source language for a simple compiler

More information

Quiz Start Time: 09:34 PM Time Left 82 sec(s)

Quiz Start Time: 09:34 PM Time Left 82 sec(s) Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects CmSc 150 Fundamentals of Computing I Lesson 28: Introduction to Classes and Objects in Java 1. Classes and Objects True object-oriented programming is based on defining classes that represent objects with

More information

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this

More information

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang

Glossary. For Introduction to Programming Using Python By Y. Daniel Liang Chapter 1 Glossary For Introduction to Programming Using Python By Y. Daniel Liang.py Python script file extension name. assembler A software used to translate assemblylanguage programs into machine code.

More information

PREPARING FOR THE FINAL EXAM

PREPARING FOR THE FINAL EXAM PREPARING FOR THE FINAL EXAM CS 1110: FALL 2017 This handout explains what you have to know for the final exam. Most of the exam will include topics from the previous two prelims. We have uploaded the

More information