Lecture 07: Python Generators, Iterators, and Decorators

Size: px
Start display at page:

Download "Lecture 07: Python Generators, Iterators, and Decorators"

Transcription

1 BI296: Linux and Shell Programming Lecture 07: Python Generators, Iterators, and Decorators Maoying,Wu Dept. of Bioinformatics & Biostatistics Shanghai Jiao Tong University Spring, 2017 Maoying Wu (CBB) BI296-Lec05 Spring, / 44

2 Lecture Outline Genterator ( 生成器 ) Concepts ( 概念 ) yield Python Class (Python 类 ) Object-oriented programming (OOP) Class concepts ( 类的一些概念 ) Defining a class ( 定义类 ) Inheritance ( 类的继承 ) Decorators (Python 装饰器 ) What is decorator ( 装饰器的概念 ) Defining a decorator( 定义装饰器 ) Using a decorator ( 使用装饰器 ) Decorators with parameters ( 带参数的装饰器 ) The other types of decorators ( 其他类型的装饰器 ) Maoying Wu (CBB) BI296-Lec05 Spring, / 44

3 Next we will talk about... 1 Generators 2 Classes 3 Decorators 4 Exception 5 Modules/Packages Maoying Wu (CBB) BI296-Lec05 Spring, / 44

4 Consider an example... Implement a function that represents the fist n non-negative integers, where n is a really big numbers. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

5 Consider an example... Implement a function that represents the fist n non-negative integers, where n is a really big numbers. Approach 1: # Build and return a list def firstn(n): num, nums = 0, [] while num < n: nums.append(num) num += 1 return nums sum_of_first_n = sum(firstn( )) Crash? Maoying Wu (CBB) BI296-Lec05 Spring, / 44

6 Approach 2: Iterator sum_of_first_n Maoying Wu (CBB) = sum(firstn( )) BI296-Lec05 Spring, / 44 class firstn(object): def init (self, n): self.n = n self.num, self.nums = 0, [] def iter (self): return self # Python 3 compatibility def next (self): return self.next() def next(self): if self.num < self.n: cur, self.num = self.num, self.num+1 return cur else: raise StopIteration()

7 Approach 3: Generator def firstn(n): num = 0 while num < n: yield num num += 1 sum_of_first_n = sum(firstn( )) print sum_of_first_n Maoying Wu (CBB) BI296-Lec05 Spring, / 44

8 range vs. xrange def test1(): n=0 for i in xrange(101): n+=i return n def test2(): return sum(xrange(101)) def test3(): return sum(x for x in xrange(101)) from timeit import Timer t1=timer("test1()", "from main import test1") t2=timer("test2()", "from main import test2") t3=timer("test3()", "from main import test3") print t1.timeit( ) print t2.timeit( ) print t3.timeit( ) print t1.repeat(3, ) print t2.repeat(3, ) print t3.repeat(3, ) Maoying Wu (CBB) BI296-Lec05 Spring, / 44

9 Next we will talk about... 1 Generators 2 Classes 3 Decorators 4 Exception 5 Modules/Packages Maoying Wu (CBB) BI296-Lec05 Spring, / 44

10 Classes: Abstract of objects Up to now, we have learn such objects: Integers Floats Strings Lists Tuples Dictionaries Sets But sometimes, we want to create our own objects. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

11 Classes: Abstract of objects Up to now, we have learn such objects: Integers Floats Strings Lists Tuples Dictionaries Sets But sometimes, we want to create our own objects. But how? Maoying Wu (CBB) BI296-Lec05 Spring, / 44

12 Python: Object-oriented Programming ( 面向对象 ) One class, multiple instances ( 一个类, 多个实例 ) Class is the blueprint, while objects are the instances To define a class, you need to specify the common Attributes ( 共有属性 ) and the methods associated with the attributes( 方法定义 ) Maoying Wu (CBB) BI296-Lec05 Spring, / 44

13 Python s way In C++/Java, you need to specify the accession privileges using such modifiers like public/private/protected. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

14 Python s way In C++/Java, you need to specify the accession privileges using such modifiers like public/private/protected. Not so in Python. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

15 Python s way In C++/Java, you need to specify the accession privileges using such modifiers like public/private/protected. Not so in Python. It is much simpler in Python. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

16 Classes: A simple example >>> # define class: >>> class Leaf:... pass >>> >>> # instantiate object >>> leaf = Leaf() >>> >>> print leaf < main.leaf instance at 0x10049df80> Maoying Wu (CBB) BI296-Lec05 Spring, / 44

17 Initializing an object ( 初始化对象 ) Constructor ( 构造方法 ) A class is instantiated by defining the init method. In Python each class has only one such constructor method. class Leaf: def init (self, color): self.color = color # private attribute redleaf = Leaf( red ) blueleaf = Leaf( blue ) print redleaf.color # red Maoying Wu (CBB) BI296-Lec05 Spring, / 44

18 self class Leaf: def init ( self, color): self.color = color # private attribute The self parameter seems strange at first sight. It refers to the the object (instance) itself. Hence self.color = color sets the color of the object self.color equal to the variable color. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

19 Another example Classes have methods (similar to functions) class Stock(): def init (self, name, symbol, prices=[]): self.name = name self.symbol = symbol self.prices = prices def highest_price(self): if len(self.prices) == 0: return MISSING PRICES return max(self.prices) apple = Stock( Apple, APPL, [500.43, ]) print apple.highest_price() Maoying Wu (CBB) BI296-Lec05 Spring, / 44

20 Another example Classes have methods (similar to functions) class Stock(): def init (self, name, symbol, prices=[]): self.name = name self.symbol = symbol self.prices = prices def highest_price(self): if len(self.prices) == 0: return MISSING PRICES return max(self.prices) apple = Stock( Apple, APPL, [500.43, ]) print apple.highest_price() Recall: list.append() or dict.items(). These are simply class methods! Maoying Wu (CBB) BI296-Lec05 Spring, / 44

21 Class attributes An example class Leaf: n_leafs = 0 # class attribute: shared def init (self, color): self.color = color # object attribute Leaf.n_leafs += 1 redleaf = Leaf( red ) blueleaf = Leaf( blue ) print redleaf.color # red print Leaf.n_leafs # 2 Class attributes are shared among all objects of that class. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

22 Class hierarchy through inheritance It can be useful (especially in larger projects) to have a hierarchy of classes. Example Animal Bird Hawk Seagull... Pet Dog Cat Maoying Wu (CBB) BI296-Lec05 Spring, / 44

23 Inheritance Animal Suppose we first define an abstract class class Animal(object): def init (self, n_legs, color): self.n_legs = n_legs self.color = color def make_noise(self): print noise Maoying Wu (CBB) BI296-Lec05 Spring, / 44

24 Inheritance Dog We can define sub classes and inherit from another class. class Dog(Animal): def init (self, color, name): Animal. init (self, 4, color) self.name = name def make_noise(self): print self.name + : + woof bird = Animal(2, white ) bird.make_noise() # noise brutus = Dog( black, Brutus ) brutus.make_noise() # Brutus: woof shelly = Dog( white, Shelly ) shelly.make_noise() # Shelly: woof Maoying Wu (CBB) BI296-Lec05 Spring, / 44

25 Base methods Some methods to override init : Constructor repr : Represent the object (machine) str : Represent the object (human) cmp : Compare Maoying Wu (CBB) BI296-Lec05 Spring, / 44

26 More useful methods Some more on this later! contains for the in keyword iter and next for iterators Maoying Wu (CBB) BI296-Lec05 Spring, / 44

27 Class: Example Rational numbers Implementing Rational numbers class Rational: pass Maoying Wu (CBB) BI296-Lec05 Spring, / 44

28 Setup What information should the class hold? Maoying Wu (CBB) BI296-Lec05 Spring, / 44

29 Setup What information should the class hold? Numerator Denominator Maoying Wu (CBB) BI296-Lec05 Spring, / 44

30 Init Let s start coding Implement the init method Maoying Wu (CBB) BI296-Lec05 Spring, / 44

31 Init Let s start coding Implement the init method class Rational: def init (self, p, q=1): self.p = p self.q = q Maoying Wu (CBB) BI296-Lec05 Spring, / 44

32 Issues Issues? class Rational: def init (self, p, q=1): self.p = p self.q = q Maoying Wu (CBB) BI296-Lec05 Spring, / 44

33 Issues Issues? class Rational: def init (self, p, q=1): self.p = p self.q = q Ignore the division by 0 for now, more on that later. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

34 Greatest common divisor (GCD) and 1 2 are the same rational. Implement a gcd(a, b) function that computes the greatest common divisor of a and b. def gcd(a, b): if b == 0: return a else: return gcd(b, a%b) Exercise: Verify Euclidean Algorithm Maoying Wu (CBB) BI296-Lec05 Spring, / 44

35 Greatest common divisor (GCD) Solution class Rational: def init (self, p, q=1): g = gcd(p, q) self.p = p / g self.q = q / g Why is this awesome? Maoying Wu (CBB) BI296-Lec05 Spring, / 44

36 Representing your class: Operator overloading Implement repr or str early to print Debugging Maoying Wu (CBB) BI296-Lec05 Spring, / 44

37 Operator overloading: Adding two Rationals Add Rationals just like Ints and Doubles? Rational(10,2) + Rational(4,3) To use +, we implement the add method class Rational: #... def add (self, other): p = self.p * other.q + other.p * self.q q = self.q * other.q return Rational(p, q) #... Maoying Wu (CBB) BI296-Lec05 Spring, / 44

38 Operator overloading: Comparisons cmp compares objects If self is smaller than other, return -1 If self and other are equal, return 0 If self is larger than other, return 1 Maoying Wu (CBB) BI296-Lec05 Spring, / 44

39 Operator overloading: Comparisons cmp compares objects If self is smaller than other, return -1 If self and other are equal, return 0 If self is larger than other, return 1 Sometimes we achieve this by calling the builtin function cmp on some properties of the instances. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

40 More on Operator Overloading init () changes how our classes initialized themselves. str () changes how our instances became strings. add () controls how instances add themselves together and with others. radd () defines the reverse adding essential for calling sum(). le () lt () < ge () gt () > eq () == ne () iadd () + = isub () = imul () = idiv () / = Maoying Wu (CBB) BI296-Lec05 Spring, / 44

41 Next we will talk about... 1 Generators 2 Classes 3 Decorators 4 Exception 5 Modules/Packages Maoying Wu (CBB) BI296-Lec05 Spring, / 44

42 What is a decorator ( 装饰器的定义 ) Decorator is a declaration of special types. Decorator can be attached to declaration of class, method, accessor, property and parameters. A decorator is a function, which takes a function as a parameter and return another function as return value Maoying Wu (CBB) BI296-Lec05 Spring, / 44

43 High-order function Debug information def login(): print in login def printdebug(func): print enter the login func() print exit the login printdebug(login) Maoying Wu (CBB) BI296-Lec05 Spring, / 44

44 A more decent coding style... def login(): print in login def printdebug(func): def decorator(): print enter the login func() print exit the login return decorator # function as return value # fuction is assigned to variable debug_login = printdebug(login) # call the returned function debug_login() Maoying Wu (CBB) BI296-Lec05 Spring, / 44

45 More decent... Python solution: a syntax sugar ( 语法糖 ) def printdebug(func): def decorator(): print enter the login func() print exit the login return # combine the printdebug and login def login(): print in login login() # make the calling point more intuitive Maoying Wu (CBB) BI296-Lec05 Spring, / 44

46 Multiple decorators sandwich() Maoying Wu (CBB) BI296-Lec05 Spring, / 44 def bread(func): def wrapper(): print("</ \>") func() print("<\ />") return wrapper def ingredients(func): def wrapper(): print("#tomatoes#") func() print("salad") def sandwich(food="--ham--"): print(food)

47 Next we will talk about... 1 Generators 2 Classes 3 Decorators 4 Exception 5 Modules/Packages Maoying Wu (CBB) BI296-Lec05 Spring, / 44

48 Error Handling ( 错误处理 ) try: pass except Exception1: pass except Exception2: pass else: pass finally: pass Handling the ERROR/EXCEPTION except Exception1 will catch the known ERROR/EXCEPTON else will catch the unknown ERROR/EXCEPTION finally will execute the code finally regardless of the ERROR/EXCEPTION. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

49 Error Handling: Example try: x = 1/0 except ZeroDivisionError: print "Failed to devided by zero" x = finally: pass Maoying Wu (CBB) BI296-Lec05 Spring, / 44

50 Next we will talk about... 1 Generators 2 Classes 3 Decorators 4 Exception 5 Modules/Packages Maoying Wu (CBB) BI296-Lec05 Spring, / 44

51 How to define a module? What is a module? Maoying Wu (CBB) BI296-Lec05 Spring, / 44

52 How to define a module? What is a module? A module is a.py file which hosts some constants, functions, classes and etc. Then how to define a module? Maoying Wu (CBB) BI296-Lec05 Spring, / 44

53 How to define a module? What is a module? A module is a.py file which hosts some constants, functions, classes and etc. Then how to define a module? It s easy. It s simply the encapsulation of the functions and classes in a single.py file. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

54 How to create a package? What is a python package? Maoying Wu (CBB) BI296-Lec05 Spring, / 44

55 How to create a package? What is a python package? A python package is a directory to host multiple modules and subpackages. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

56 How to create a package? What is a python package? A python package is a directory to host multiple modules and subpackages. Multiple module files are needed. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

57 How to create a package? What is a python package? A python package is a directory to host multiple modules and subpackages. Multiple module files are needed. But the most important thing is the init.py file, which can be empty. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

58 Exercise 1 Write a class Vector 2 Write a class Matrix 3 Write a class Distance to compute the distance between two vectors, two matrices, etc. 4 Encapsulate the above modules into a package. 5 Write an example code to call the above module. Maoying Wu (CBB) BI296-Lec05 Spring, / 44

CME 193: Introduction to Scientific Python Lecture 4: File I/O and Classes

CME 193: Introduction to Scientific Python Lecture 4: File I/O and Classes CME 193: Introduction to Scientific Python Lecture 4: File I/O and Classes Sven Schmit stanford.edu/~schmit/cme193 4: File I/O and Classes 4-1 Feedback form Please take a moment to fill out feedback form

More information

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators

CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators CME 193: Introduction to Scientific Python Lecture 6: Classes and iterators Sven Schmit stanford.edu/~schmit/cme193 6: Classes and iterators 6-1 Contents Classes Generators and Iterators Exercises 6: Classes

More information

CME 193: Introduction to Scientific Python Lecture 5: Object Oriented Programming

CME 193: Introduction to Scientific Python Lecture 5: Object Oriented Programming CME 193: Introduction to Scientific Python Lecture 5: Object Oriented Programming Nolan Skochdopole stanford.edu/class/cme193 5: Object Oriented Programming 5-1 Contents Classes Numpy Exercises 5: Object

More information

CME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O

CME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O CME 193: Introduction to Scientific Python Lecture 4: Strings and File I/O Nolan Skochdopole stanford.edu/class/cme193 4: Strings and File I/O 4-1 Contents Strings File I/O Classes Exercises 4: Strings

More information

file:///users/jacobperricone/desktop/stanford/cme193_s18/cme193/lectures/presentations/lecture4.slides.html?print-pdf%20=%20true#/ 1/94

file:///users/jacobperricone/desktop/stanford/cme193_s18/cme193/lectures/presentations/lecture4.slides.html?print-pdf%20=%20true#/ 1/94 CME 193 Introduction to Scienti c Python Spring 2018 Lecture 4 File I/O and Object Oriented Programming file:///users/jacobperricone/desktop/stanford/cme193_s18/cme193/lectures/presentations/lecture4.slides.html?print-pdf%20=%20true#/

More information

COMPSCI 105 S Principles of Computer Science. Classes 3

COMPSCI 105 S Principles of Computer Science. Classes 3 S2 2017 Principles of Computer Science Classes 3 Exercise } Exercise } Create a Student class: } The Student class should have three attributes: id, last_name, and first_name. } Create a constructor to

More information

Computational Mathematics with Python

Computational Mathematics with Python Numerical Analysis, Lund University, 2015 1 Computational Mathematics with Python Unit 7: Object oriented programming with classes Numerical Analysis, Lund University Lecturer: Claus Führer 2015 Classes

More information

Computational Mathematics with Python

Computational Mathematics with Python Numerical Analysis, Lund University, 2012 1 Computational Mathematics with Python Unit 8: Object oriented programming with classes Numerical Analysis, Lund University Claus Führer, Olivier Verdier, Tony

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

Operator Overloading. a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum

Operator Overloading. a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum Operator Overloading 1 OOP to count Flops a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum 2 Quaternions hypercomplex numbers application in computer

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

CMSC201 Computer Science I for Majors

CMSC201 Computer Science I for Majors CMSC201 Computer Science I for Majors Lecture 25 Classes All materials copyright UMBC and Dr. Katherine Gibson unless otherwise noted Run time Last Class We Covered Run time of different algorithms Selection,

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

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

Lecture 06: Compound Data Types in Python

Lecture 06: Compound Data Types in Python BI296: Linux and Shell Programming Lecture 06: Compound Data Types in Python Maoying,Wu ricket.woo@gmail.com Dept. of Bioinformatics & Biostatistics Shanghai Jiao Tong University Spring, 2017 Maoying Wu

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

Creating a new data type

Creating a new data type Appendix B Creating a new data type Object-oriented programming languages allow programmers to create new data types that behave much like built-in data types. We will explore this capability by building

More information

Introduction to Programming Using Java (98-388)

Introduction to Programming Using Java (98-388) Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;

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

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented

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

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

Object Oriented Programming

Object Oriented Programming Object Oriented Programming Objectives To review the concepts and terminology of object-oriented programming To discuss some features of objectoriented design 1-2 Review: Objects In Java and other Object-Oriented

More information

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming

ECE 364 Software Engineering Tools Laboratory. Lecture 7 Python: Object Oriented Programming ECE 364 Software Engineering Tools Laboratory Lecture 7 Python: Object Oriented Programming 1 Lecture Summary Object Oriented Programming Concepts Object Oriented Programming in Python 2 Object Oriented

More information

Python for Finance. Advanced Features. Andras Niedermayer

Python for Finance. Advanced Features. Andras Niedermayer Python for Finance Advanced Features Andras Niedermayer Objects of Interest object oriented programming (Wikipedia) Definition (Object-oriented Programming) Object-oriented programming (OOP) is a programming

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

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for This Lecture Assignments Prelim 2 A4 is now graded Mean: 90.4 Median: 93 Std Dev: 10.6 Mean: 9 hrs Median: 8 hrs Std Dev: 4.1 hrs A5 is also graded

More information

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018

Fundamentals of Programming (Python) Object-Oriented Programming. Ali Taheri Sharif University of Technology Spring 2018 Fundamentals of Programming (Python) Object-Oriented Programming Ali Taheri Sharif University of Technology Outline 1. Python Data Types 2. Classes and Objects 3. Defining Classes 4. Working with Objects

More information

CSCE 110: Programming I

CSCE 110: Programming I CSCE 110: Programming I Sample Questions for Exam #1 February 17, 2013 Below are sample questions to help you prepare for Exam #1. Make sure you can solve all of these problems by hand. For most of the

More information

Programming I. Course 9 Introduction to programming

Programming I. Course 9 Introduction to programming Programming I Course 9 Introduction to programming What we talked about? Modules List Comprehension Generators Recursive Functions Files What we talk today? Object Oriented Programming Classes Objects

More information

Shell Programming (Part 2)

Shell Programming (Part 2) i i Systems and Internet Infrastructure Security Institute for Networking and Security Research Department of Computer Science and Engineering Pennsylvania State University, University Park, PA Shell Programming

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

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

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science

PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science PLEASE HAND IN UNIVERSITY OF TORONTO Faculty of Arts and Science AUGUST EXAMINATIONS CSC 108H1Y Instructor: Daniel Zingaro Duration three hours PLEASE HAND IN Examination Aids: None. Student Number: Last

More information

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 10 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

PIC 16: Iterators and Generators

PIC 16: Iterators and Generators PIC 16: Iterators and Generators Assigned 10/9/2018. To be completed before lecture 10/12/2018. Intended Learning Outcomes. By the end of this preparatory assignment, students should be able to: implement

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

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses Lecture 21 Programming with Subclasses Announcements for Today Reading Today: See reading online Tuesday: Chapter 7 Prelim, Nov 9 th 7:30-9:00 Material up to Today Review has been posted Recursion + Loops

More information

Welcome to CSC148! Introduction to Computer Science

Welcome to CSC148! Introduction to Computer Science Welcome to CSC148! Introduction to Computer Science Amir H. Chinaei, Summer 2016 ahchinaei@cs.toronto.edu http://www.cs.toronto.edu/~ahchinaei/ Office hours: R 10 BA4222 Today Course Outline (bird s-eye

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

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

Introduction to Python programming, II

Introduction to Python programming, II GC3: Grid Computing Competence Center Introduction to Python programming, II (with a hint of MapReduce) Riccardo Murri Grid Computing Competence Center, University of Zurich Oct. 10, 2012 Today s class

More information

CS 11 python track: lecture 2

CS 11 python track: lecture 2 CS 11 python track: lecture 2 Today: Odds and ends Introduction to object-oriented programming Exception handling Odds and ends List slice notation Multiline strings Docstrings List slices (1) a = [1,

More information

Page. User. Sorting Mini-HOW TO. Search Titles Text. More Actions: HowTo Sorting. HowTo/Sorting

Page. User. Sorting Mini-HOW TO. Search Titles Text. More Actions: HowTo Sorting. HowTo/Sorting 1 of 8 01/09/2013 04:30 PM This is Google's cache of http://wiki.python.org/moin/howto/sorting/. It is a snapshot of the page as it appeared on Jan 3, 2013 05:54:53 GMT. The current page could have changed

More information

Lecture 18. Classes and Types

Lecture 18. Classes and Types Lecture 18 Classes and Types Announcements for Today Reading Today: See reading online Tuesday: See reading online Prelim, Nov 6 th 7:30-9:30 Material up to next class Review posted next week Recursion

More information

[CHAPTER] 1 INTRODUCTION 1

[CHAPTER] 1 INTRODUCTION 1 FM_TOC C7817 47493 1/28/11 9:29 AM Page iii Table of Contents [CHAPTER] 1 INTRODUCTION 1 1.1 Two Fundamental Ideas of Computer Science: Algorithms and Information Processing...2 1.1.1 Algorithms...2 1.1.2

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

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++

I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination. June, 2015 BCS-031 : PROGRAMMING IN C ++ No. of Printed Pages : 3 I BCS-031 BACHELOR OF COMPUTER APPLICATIONS (BCA) (Revised) Term-End Examination 05723. June, 2015 BCS-031 : PROGRAMMING IN C ++ Time : 3 hours Maximum Marks : 100 (Weightage 75%)

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

Objectives Getting Started What Is Computer Science? Review of Basic Python Summary. Introduction 1/25/06. Introduction

Objectives Getting Started What Is Computer Science? Review of Basic Python Summary. Introduction 1/25/06. Introduction Brad Miller David Ranum 1/25/06 Outline Objectives 1 Objectives 2 3 What Is Programming? Why Study Data Structures and Abstract Data Types? Why Study Algorithms? 4 with Data Object-Oriented Programming

More information

Chapter 2: Java OO II. Yang Wang wyang AT njnet.edu.cn

Chapter 2: Java OO II. Yang Wang wyang AT njnet.edu.cn Chapter 2: Java OO II Yang Wang wyang AT njnet.edu.cn Outline Abstraction Abstract Class Interface Inheritance Polymorphism Abstraction Abstraction What is Abstraction? An abstraction is a general idea

More information

Download Python from Any version will do for this class

Download Python from  Any version will do for this class Let s Start Python Let s Start! Download Python from www.python.org Any version will do for this class By and large they are all mutually compatible Recommended version: 2.1.1 or 2.2 Oldest version still

More information

Sorting HOW TO Release 2.7.6

Sorting HOW TO Release 2.7.6 Sorting HOW TO Release 2.7.6 Guido van Rossum Fred L. Drake, Jr., editor November 10, 2013 Python Software Foundation Email: docs@python.org Contents 1 Sorting Basics i 2 Key Functions ii 3 Operator Module

More information

20. More Complicated Classes. A Class For Manipulating Fractions. A Class For Manipulating Fractions 4/19/2016. Let s Define a Class to Do This Stuff

20. More Complicated Classes. A Class For Manipulating Fractions. A Class For Manipulating Fractions 4/19/2016. Let s Define a Class to Do This Stuff 4/9/26 2. More Complicated Classes Class For Manipulating Fractions Topics: Example: The class Fraction Operator Overloading Class Invariants Example: The class SimpleDate Class Variables deepcopy You

More information

Week 2. Classes and Objects

Week 2. Classes and Objects Week 2 Classes and Objects Special thanks to Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0

More information

Review 2. Classes and Subclasses

Review 2. Classes and Subclasses Review 2 Classes and Subclasses Class Definition class (): """Class specification""" class variables (format: Class.variable) initializer ( init ) special method definitions

More information

CS 234 Python Review Part 2

CS 234 Python Review Part 2 CS 234 Python Review Part 2 Recap import function: define, return boolean, conditional, branching loop: for, range, while file: open, close, readlines string: split Classes Define blueprint for a custom

More information

CSC148H Week 1 >> COURSE INFORMATION, RECAP, OOP. Sadia Rain Sharmin Week of May 7, 2018

CSC148H Week 1 >> COURSE INFORMATION, RECAP, OOP. Sadia Rain Sharmin Week of May 7, 2018 CSC148H Week 1 >> COURSE INFORMATION, RECAP, OOP Sadia Rain Sharmin Week of May 7, 2018 Welcome! What is CSC148 about? - Designing programs using OO programming principles - Reasoning about efficiency

More information

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern CSE 399-004: Python Programming Lecture 12: Decorators April 9, 200 http://www.seas.upenn.edu/~cse39904/ Announcements Projects (code and documentation) are due: April 20, 200 at pm There will be informal

More information

CS 11 python track: lecture 4

CS 11 python track: lecture 4 CS 11 python track: lecture 4 Today: More odds and ends assertions "print >>" syntax more on argument lists functional programming tools list comprehensions More on exception handling More on object-oriented

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

CSI33 Data Structures

CSI33 Data Structures Outline Department of Mathematics and Computer Science Bronx Community College September 6, 2017 Outline Outline 1 Chapter 2: Data Abstraction Outline Chapter 2: Data Abstraction 1 Chapter 2: Data Abstraction

More information

Advanced topics, part 2

Advanced topics, part 2 CS 1 Introduction to Computer Programming Lecture 24: December 5, 2012 Advanced topics, part 2 Last time Advanced topics, lecture 1 recursion first-class functions lambda expressions higher-order functions

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

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

Lecture 18. Methods and Operations

Lecture 18. Methods and Operations Lecture 18 Methods and Operations Announcements for This Lecture Assignments A4 Due Thursday at midnight Hopefully you are on Task 4 Extra consultants available Will post A5 on Thursday Written assignment

More information

Fundamentals of Programming. Week 11 - Lecture 1: OOP Part 2.

Fundamentals of Programming. Week 11 - Lecture 1: OOP Part 2. 15-112 Fundamentals of Programming Week 11 - Lecture 1: OOP Part 2. March 29, 2016 >> Inheritance Today s Menu (Wrapping up OOP) - Employee and Student as subclasses of Person - isintance( ) vs type( )

More information

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I

Object-Oriented Programming (OOP) Basics. CSCI 161 Introduction to Programming I Object-Oriented Programming (OOP) Basics CSCI 161 Introduction to Programming I Overview Chapter 8 in the textbook Building Java Programs, by Reges & Stepp. Review of OOP History and Terms Discussion of

More information

Lecture 15: Intro to object oriented programming (OOP); Linked lists

Lecture 15: Intro to object oriented programming (OOP); Linked lists Extended Introduction to Computer Science CS1001.py Lecture 15: Intro to object oriented programming (OOP); Linked lists Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants: Michal Kleinbort,

More information

Extended Introduction to Computer Science CS1001.py Lecture 15: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP)

Extended Introduction to Computer Science CS1001.py Lecture 15: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP) Extended Introduction to Computer Science CS1001.py Lecture 15: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP) Instructors: Benny Chor, Amir Rubinstein Teaching Assistants:

More information

Extended Introduction to Computer Science CS1001.py Lecture 13: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP)

Extended Introduction to Computer Science CS1001.py Lecture 13: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP) Extended Introduction to Computer Science CS1001.py Lecture 13: Integer gcd: Euclid's Algorithm; Intro to object oriented programming (OOP) Instructors: Daniel Deutch, Amir Rubinstein Teaching Assistants:

More information

Lecture #12: Quick: Exceptions and SQL

Lecture #12: Quick: Exceptions and SQL UC Berkeley EECS Adj. Assistant Prof. Dr. Gerald Friedland Computational Structures in Data Science Lecture #12: Quick: Exceptions and SQL Administrivia Open Project: Starts Monday! Creative data task

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

CSCI 355 LAB #2 Spring 2004

CSCI 355 LAB #2 Spring 2004 CSCI 355 LAB #2 Spring 2004 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

三 依赖注入 (dependency injection) 的学习

三 依赖注入 (dependency injection) 的学习 三 依赖注入 (dependency injection) 的学习 EJB 3.0, 提供了一个简单的和优雅的方法来解藕服务对象和资源 使用 @EJB 注释, 可以将 EJB 存根对象注入到任何 EJB 3.0 容器管理的 POJO 中 如果注释用在一个属性变量上, 容器将会在它被第一次访问之前赋值给它 在 Jboss 下一版本中 @EJB 注释从 javax.annotation 包移到了 javax.ejb

More information

CSCI 355 Lab #2 Spring 2007

CSCI 355 Lab #2 Spring 2007 CSCI 355 Lab #2 Spring 2007 More Java Objectives: 1. To explore several Unix commands for displaying information about processes. 2. To explore some differences between Java and C++. 3. To write Java applications

More information

Exceptions. raise type(message) raise Exception(message)

Exceptions. raise type(message) raise Exception(message) Classes Special thanks to Roy McElmurry, Scott Shawcroft, Ryan Tucker, and Paul Beck for their work on these slides. Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/.0

More information

Try and Error. Python debugging and beautification

Try and Error. Python debugging and beautification Try and Error Python debugging and beautification What happens when something goes wrong Catching exceptions In order to handle errors, you can set up exception handling blocks in your code. The keywords

More information

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions Outline 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating

More information

Shell programming. Introduction to Operating Systems

Shell programming. Introduction to Operating Systems Shell programming Introduction to Operating Systems Environment variables Predened variables $* all parameters $# number of parameters $? result of last command $$ process identier $i parameter number

More information

INHERITANCE AND INTERFACES 7

INHERITANCE AND INTERFACES 7 INHERITANCE AND INTERFACES 7 COMPUTER SCIENCE 61A October 16, 2014 1 Inheritance Today, we explore another powerful tool that comes with object-oriented programming inheritance. Suppose we want to write

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

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 15 Class Relationships Outline Problem: How can I create and store complex objects? Review of static methods Consider static variables What about objects

More information

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department

Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department Al al-bayt University Prince Hussein Bin Abdullah College for Information Technology Computer Science Department 0901212 Python Programming 1 st Semester 2014/2015 Course Catalog This course introduces

More information

PREPARING FOR PRELIM 2

PREPARING FOR PRELIM 2 PREPARING FOR PRELIM 2 CS 1110: FALL 2012 This handout explains what you have to know for the second prelim. There will be a review session with detailed examples to help you study. To prepare for the

More information

Exceptions & a Taste of Declarative Programming in SQL

Exceptions & a Taste of Declarative Programming in SQL Exceptions & a Taste of Declarative Programming in SQL David E. Culler CS8 Computational Structures in Data Science http://inst.eecs.berkeley.edu/~cs88 Lecture 12 April 18, 2016 Computational Concepts

More information

Control Structures. CIS 118 Intro to LINUX

Control Structures. CIS 118 Intro to LINUX Control Structures CIS 118 Intro to LINUX Basic Control Structures TEST The test utility, has many formats for evaluating expressions. For example, when given three arguments, will return the value true

More information

callback, iterators, and generators

callback, iterators, and generators callback, iterators, and generators 1 Adding a Callback Function a function for Newton s method a function of the user to process results 2 A Newton Iterator defining a counter class refactoring the Newton

More information

Unit E Step-by-Step: Programming with Python

Unit E Step-by-Step: Programming with Python Unit E Step-by-Step: Programming with Python Computer Concepts 2016 ENHANCED EDITION 1 Unit Contents Section A: Hello World! Python Style Section B: The Wacky Word Game Section C: Build Your Own Calculator

More information

CS 251 Intermediate Programming Methods and More

CS 251 Intermediate Programming Methods and More CS 251 Intermediate Programming Methods and More Brooke Chenoweth University of New Mexico Spring 2018 Methods An operation that can be performed on an object Has return type and parameters Method with

More information

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed

COMP200 INTERFACES. OOP using Java, from slides by Shayan Javed 1 1 COMP200 INTERFACES OOP using Java, from slides by Shayan Javed Interfaces 2 ANIMAL picture food sleep() roam() makenoise() eat() 3 ANIMAL picture food sleep() roam() makenoise() eat() 4 roam() FELINE

More information

Variable and Data Type I

Variable and Data Type I The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 2 Variable and Data Type I Eng. Ibraheem Lubbad February 18, 2017 Variable is reserved

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

10266 Programming in C Sharp with Microsoft Visual Studio 2010

10266 Programming in C Sharp with Microsoft Visual Studio 2010 10266 Programming in C Sharp with Microsoft Visual Studio 2010 Course Number: 10266A Category: Visual Studio 2010 Duration: 5 days Course Description The course focuses on C# program structure, language

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

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries

Syllabus & Curriculum for Certificate Course in Java. CALL: , for Queries 1 CONTENTS 1. Introduction to Java 2. Holding Data 3. Controllin g the f l o w 4. Object Oriented Programming Concepts 5. Inheritance & Packaging 6. Handling Error/Exceptions 7. Handling Strings 8. Threads

More information

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards

MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL. John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards MATVEC: MATRIX-VECTOR COMPUTATION LANGUAGE REFERENCE MANUAL John C. Murphy jcm2105 Programming Languages and Translators Professor Stephen Edwards Language Reference Manual Introduction The purpose of

More information

Lecture Notes, CSE 232, Fall 2014 Semester

Lecture Notes, CSE 232, Fall 2014 Semester Lecture Notes, CSE 232, Fall 2014 Semester Dr. Brett Olsen Week 11 - Number Theory Number theory is the study of the integers. The most basic concept in number theory is divisibility. We say that b divides

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

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led

PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO Course: 10550A; Duration: 5 Days; Instructor-led CENTER OF KNOWLEDGE, PATH TO SUCCESS Website: PROGRAMMING IN VISUAL BASIC WITH MICROSOFT VISUAL STUDIO 2010 Course: 10550A; Duration: 5 Days; Instructor-led WHAT YOU WILL LEARN This course teaches you

More information