ITP Programming Languages Chapter 2 Building Abstractions with Data 2.5 Object-Oriented Programming 1. Polymorphism repr, str Interface

Size: px
Start display at page:

Download "ITP Programming Languages Chapter 2 Building Abstractions with Data 2.5 Object-Oriented Programming 1. Polymorphism repr, str Interface"

Transcription

1 ITP Programming Languages Chapter 2 Building Abstractions with Data 2.5 Object-Oriented Programming 1. Polymorphism repr, str 2. Interface 4. Example Complex number Major references: 1. Structure and Interpretation of Computer Programs(SICP) by Abelson and Sussman, MIT Composing Programs by John DeNero, Google 2. MITx OPENCOURSEWARE(OCW) 6.00 SC Lecture 3. UC Berkley CS61A Lecture 4. Python, Wikipedia and many on-line resources. Prof. Youngsup Kim, idebtor@handong.edu, 2014 Programming Languages, CSEE Dept., Handong Global University

2 may be thoroughly equipped for every good work.

3 All Scripture is God-breathed and is useful for teaching, rebuking, correcting and training in righteousness, so that the man of God may be thoroughly equipped for every good work. (2Tim 3:16)

4 Object-Oriented Programming Object Abstraction String Representations 4

5 String Representations An object value should behave like the kind of data it is meant to represent. For instance, by producing a string representation of itself Strings are important: they represent language and programs In Python, all objects produce two string representations: The str is legible to humans. The repr is legible to the Python interpreter. The str and repr strings are often the same, but not always. 5

6 The repr String for an Object The repr function returns a Python expression (a string) that evaluates to an equal object. repr(object) -> string Return the canonical string representation of the object. For most object types, eval(repr(object)) == object. The result of calling repr on a value is what Python prints in an interactive session. >>> 12e >>> print(repr(12e12)) Some objects do not have a simple Python-readable string. >>> repr(min) '<built-in function min>' 6

7 The str String for an Object Human interpretable strings are useful as well: >>> import datetime >>> today = datetime.date(2014, 11, 20) >>> repr(today) 'datetime.date(2014, 11, 20)' >>> str(today) ' ' The result of calling str on the value of an expression is what Python prints using the print function: >>> print(today)

8 The str String for an Object (Demo) >>> from datetime import date >>> date >>> today = datetime.date(2014, 11, 20) >>> today datetime.date(2014, 11, 20) >>> repr(today) 'datetime.date(2014, 11, 20)' >>> repr(today) 'datetime.date(2014, 11, 20)' >>> print(today) >>> print(str(today)) >>> str(today) ' ' 8

9 Object-Oriented Programming Object Abstraction String Representations Polymorphic Functions 9

10 Polymorphic Functions A function that applies to many (poly) different forms (morph) of data. str and repr are both polymorphic; they apply to any object. repr invokes a zero-argument method repr on its argument. >>> today. repr () 'datetime.date(2014, 11, 20)' str invokes a zero-argument method str on its argument. >>> today. str () ' ' 10

11 Implementing repr and str The behavior of repr is slightly more complicated than invoking repr on its argument: An instance attribute called repr is ignored! Only class attributes are found. Question: How would we implement this behavior? The behavior of str is also complicated: An instance attribute called str is ignored. If no str attribute is found, uses repr string. Question: How would we implement this behavior? str is a class, not a function [Demo] 11

12 Demo class Bear: def repr (self): return 'Bear()' >>> Bear() Bear() >>> oski = Bear() >>> oski. repr () 'Bear()' >>> oski Bear() >>> 12

13 Demo class Bear: def repr (self): return 'Bear()' def print_bear(): oski = Bear() print(oski) print(str(oski)) print(repr(oski)) print(oski. repr ()) print(oski. str()) >>> print_bear() Bear() Bear() Bear() Bear() Bear() >>> 13

14 Demo class Bear: def repr (self): return 'Bear()' def str (self): return 'a bear' def print_bear(): oski = Bear() print(oski) print(str(oski)) print(repr(oski)) print(oski. repr ()) print(oski. str ()) >>> print_bear() a bear a bear Bear() Bear() a bear >>> 14

15 Demo class Bear: def init (self): self. repr =lambda:'oski' self. str =lambda:'this bear instance' def repr (self): return 'Bear()' def str (self): return 'a bear' def print_bear(): oski = Bear() print(oski) print(str(oski)) print(repr(oski)) print(oski. repr ()) print(oski. str ()) defining instance methods: repr, str >>> print_bear() a bear a bear Bear() oski this bear instance >>> There is a subtle difference between repr and repr, str and str. These search instance methods first, while others goes to class attributes first repr, str 15

16 Demo class Bear: def init (self): self. repr =lambda:'oski' self. str =lambda:'this bear' def repr (self): return 'Bear()' def str (self): return 'a bear' def print_bear(): oski = Bear() print(oski) print(str(oski)) print(repr(oski)) print(oski. repr ()) print(oski. str ()) def repr(x): type(x). repr (x) def str(x): t = type(x) if hasattr(t, ' str '): return t. str (x) else: return repr(x) >>> print_bear() a bear a bear Bear() oski this bear instance >>> This implementation works exactly how the Python interpreter evaluates. 16

17 Object-Oriented Programming Object Abstraction String Representations Polymorphic Functions Interfaces 17

18 Interfaces Message passing: Objects interact by looking up attributes on each other. (passing messages) The attribute look-up rules allow different data types to respond to the same message. A shared message (attribute name) that elicits similar behavior from different object classes is a powerful method of abstraction. An interface is a set of shared messages, along with a specification of what they mean. Example: Classes that implement repr and str methods that return Python- and human-readable strings implement an interface for producing string representations. 18

19 Object-Oriented Programming Object Abstraction String Representations Polymorphic Functions Property Methods 19

20 Property Methods Often, we want the value of instance attributes to stay in sync. >>> f = Rational(3, 5) >>> f.float_value >>> f.numer = 4 No method calls! >>> f.float_value

21 Property Methods Often, we want the value of instance attributes to stay in sync. >>> f = Rational(3, 5) >>> f.float_value 0.6 >>> f.numer = 4 >>> f.float_value 0.8 No method calls!

22 Property Methods Often, we want the value of instance attributes to stay in sync. >>> f = Rational(3, 5) >>> f.float_value 0.6 >>> f.numer = 4 >>> f.float_value 0.8 >>> f.denom -= 3 >>> f.float_value 2.0 No method calls!

23 Property Methods Often, we want the value of instance attributes to stay in sync. >>> f = Rational(3, 5) >>> f.float_value 0.6 >>> f.numer = 4 >>> f.float_value 0.8 >>> f.denom -= 3 >>> f.float_value 2.0 No method calls! decorator on a method designates that it will be called whenever it is looked up on an instance. 23

24 Property Methods Often, we want the value of instance attributes to stay in sync. >>> f = Rational(3, 5) >>> f.float_value 0.6 >>> f.numer = 4 No method calls! >>> f.float_value 0.8 >>> f.denom -= 3 >>> f.float_value 2.0 Attribute acts like a method! decorator on a method designates that it will be called whenever it is looked up on an instance. It allows zero-argument methods to be called without an explicit call expression. [Demo] 24

25 Property Methods [Demo] # Rational numbers class Rational: """A mutable fraction.""" def init (self, n, denom): self.numer = n self.denom = denom def repr (self): return 'Rational({0}, {1})'.format(self.numer, self.denom) 25

26 Property Methods [Demo] # Rational numbers class Rational: """A mutable fraction.""" def init (self, n, denom): self.numer = n self.denom = denom def repr (self): return 'Rational({0}, {1})'.format(self.numer, self.denom) >>> Rational(1, 2) Rational(1, 2) 26

27 Property Methods [Demo] # Rational numbers class Rational: """A mutable fraction.""" def init (self, n, denom): self.numer = n self.denom = denom def repr (self): return 'Rational({0}, {1})'.format(self.numer, self.denom) def str (self): return '{0}/{1}'.format(self.numer, self.denom) >>> Rational(1, 2) Rational(1, 2) >>> Rational(1, 2) 1/2 27

28 Property Methods [Demo] # Rational numbers class Rational: """A mutable fraction.""" def init (self, n, denom): self.numer = n self.denom = denom def repr (self): return 'Rational({0}, {1})'.format(self.numer, self.denom) def str (self): return '{0}/{1}'.format(self.numer, self.denom) def float_value(self): return self.numer/self.denom >>> Rational(3, 5).float_value <bound method Rational.float_val >>> Rational(3, 5).float_value()

29 Property Methods [Demo] # Rational numbers class Rational: """A mutable fraction.""" def init (self, n, denom): self.numer = n self.denom = denom def repr (self): return 'Rational({0}, {1})'.format(self.numer, self.denom) def str (self): return '{0}/{1}'.format(self.numer, def float_value(self): return self.numer/self.denom >>> x = Rational(3, 5) >>> x.float_value 0.6 >>> x.numer = 4 >>> x.float_value

30 Formatting Strings with the format() Method and %s In Python 3, you can include %s inside a string and follow it with a list of values for each %s such as: >>> # Python 2 and 3 >>> 'My name is %s and I am from %s.' % ('Al', 'Houston') 'My name is Al and I am from Houston.' >>> 'My name is {0} and I am from {1}.'.format('Al', 'Houston') 'My name is Al and I am from Houston.' >>> 'My name is {1} and I am from {0}.'.format('Al', 'Houston') 'My name is Houston and I am from Al.' 'My name is {0} and I like {thing} and I am from {hometown}.'.format('al', hometown='houston', thing='cats') 'My name is Al and I like cats and I am from Houston.' >>> 'My name is {0}, {0} and I'm from {1}.'.format('Al Gore', 'Houston') 'My name is Al Gore, Al Gore and I'm from Houston.' 30

31 Formatting Strings with the format() Method and %s The general syntax for a format placeholder is %[flags][width][.precision]type 31

32 Object-Oriented Programming Object Abstraction String Representations Polymorphic Functions Property Methods Example: Complex Number Property Methods Interfaces 32

33 Multiple Representations of Abstract Data Rectangular and polar representations for complex numbers Most programs don't care about the representation. Some arithmetic operations are easier using one representation than the other. 33

34 Implementing Complex Arithmetic Assume that there are two different classes that both represent Complex numbers. Number Rectangular representation Polar representation ComplexRI(1, 1) ComplexMA(sqrt(2), pi/4) Perform arithmetic using the most convenient representation, respectively. class Complex: def add(self, other): return ComplexRI(self.real + other.real, self.imag + other.imag) def mul(self, other): return ComplexMA(self.magnitude * other.magnitude, self.angle + other.angle) 34

35 Complex Arithmetic Abstraction Barriers Parts of the program that... Treat complex numbers as... Using... Use complex numbers to perform computation whole data values x.add(y), x.mul(y) Add complex numbers real and imaginary parts real, imag, ComplexRI Multiply complex numbers magnitudes and angles magnitude, angle, ComplexMA Implementation of the Python object system 35

36 Object-Oriented Programming Object Abstraction String Representations Polymorphic Functions Property Methods Example: Complex Number Implementation 36

37 An Interface for Complex Numbers All complex numbers should have real and imag components. All complex numbers should have a magnitude and angle. All complex numbers should share an implementation of add and mul. Complex ComplexRI ComplexMA [Demo] 37

38 An Interface for Complex Numbers All complex numbers should have real and imag components. All complex numbers should have a magnitude and angle. All complex numbers should share an implementation of add and mul. Complex What is called in OOP? ComplexRI ComplexMA [Demo] 38

39 An Interface for Complex Numbers All complex numbers should have real and imag components. All complex numbers should have a magnitude and angle. All complex numbers should share an implementation of add and mul. Complex ComplexRI ComplexMA What is called in OOP? [Demo] 39

40 Complex numbers from math import atan2, sin, cos, pi class Complex: def add(self, other): return ComplexRI(self.real + other.real, self.imag + other.imag) def mul(self, other): return ComplexMA(self.magnitude * other. magnitude, self.angle + other.angle) 40

41 The Rectangular Representation class ComplexRI(Complex): """A rectangluar representation of a complex number.""" def init (self, real, imag): self.real = real self.imag = def magnitude(self): Property decorator: "Call this function on attribute look-up" return (self.real ** 2 + self.imag ** 2) ** 0.5 math.atan2(y,x): Angle x-axis and the point(x,y) def angle(self): return atan2(self.imag, self.real) def repr (self): return 'ComplexRI({0}, {1})'.format(self.real, self.imag) decorator allows zero-argument methods to be called without the standard call expression syntax, so that they appear to be simple attributes. 41

42 Complex numbers from math import atan2, sin, cos, pi class Complex: def add(self, other): return ComplexRI(self.real + other.real, self.imag + other.imag) def mul(self, other): return ComplexMA(self.magnitude * other. magnitude, self.angle + other.angle) >>> ComplexRI(1, 1) ComplexRI(1, 1) >>> x = ComplexRI(1, 1) >>> x.add(x) ComplexRI(2, 2) >>> x.add(complexri(2, 4)) ComplexRI(3, 5) 42

43 The Polar Representation class ComplexMA(Complex): """A polar represenation of a complex number""" def init (self, magnitude, angle): self.magnitude = magnitude self.angle = def real(self): return self.magnitude * def imag(self): return self.magnitude * sin(self.angle) def repr (self): return 'ComplexMA({0}, {1})'.format(self.magnitude, self.angle) 43

44 Complex numbers from math import atan2, sin, cos, pi class Complex: def add(self, other): return ComplexRI(self.real + other.real, self.imag + other.imag) def mul(self, other): return ComplexMA(self.magnitude * other. magnitude, self.angle + other.angle) >>> ComplexMA(1, 0) ComplexMA(1, 0) >>> i = ComplexRI(0, 1) >>> i.mul(i) ComplexMA(1.0, >>> x = i.mul(i) >>> x.real -1.0 >>> x.imag e-16 >>> round(x.imag) 0 44

45 Using Complex Numbers Either type of complex number can be either argument to add or mul: class Complex: def add(self, other): return ComplexRI(self.real + other.real, self.imag + other.imag) def mul(self, other): return ComplexMA(self.magnitude * other.magnitude, self.angle + other.angle) >>> from math import pi >>> ComplexRI(1, 2).add(ComplexMA(2, pi/2)) ComplexRI( , 4.0) >>> ComplexRI(0, 1).mul(ComplexRI(0, 1)) ComplexRI(0, 2) ComplexMA(0, pi/2) 45

46 Using Complex Numbers Either type of complex number can be either argument to add or mul: class Complex: def add(self, other): return ComplexRI(self.real + other.real, self.imag + other.imag) def mul(self, other): return ComplexMA(self.magnitude * other.magnitude, self.angle + other.angle) >>> from math import pi >>> ComplexRI(1, 2).add(ComplexMA(2, pi/2)) ComplexRI( , 4.0) >>> ComplexRI(0, 1).mul(ComplexRI(0, 1)) ComplexRI(0, 2) ComplexMA(0, pi/2) 46

47 Using Complex Numbers Either type of complex number can be either argument to add or mul: class Complex: def add(self, other): return ComplexRI(self.real + other.real, self.imag + other.imag) def mul(self, other): return ComplexMA(self.magnitude * other.magnitude, self.angle + other.angle) >>> from math import pi >>> ComplexRI(1, 2).add(ComplexMA(2, pi/2)) ComplexRI( , 4.0) >>> ComplexRI(0, 1).mul(ComplexRI(0, 1)) ComplexMA(1.0, ) ComplexRI(0, 2) ComplexMA(0, pi/2) 47

48 ITP Programming Languages Chapter 2 Building Abstractions with Data 2.5 Object-Oriented Programming 1. Polymorphism repr, str 2. Interface 4. Example Complex number 3.0 The Scheme Programming Language Major references: 1. Structure and Interpretation of Computer Programs(SICP) by Abelson and Sussman, MIT Composing Programs by John DeNero, Google 2. MITx OPENCOURSEWARE(OCW) 6.00 SC Lecture 3. UC Berkley CS61A Lecture 4. Python, Wikipedia and many on-line resources. Prof. Youngsup Kim, idebtor@handong.edu, 2014 Programming Languages, CSEE Dept., Handong Global University

String Representations

String Representations 61A Lecture 16 Announcements String Representations String Representations An object value should behave like the kind of data it is meant to represent For instance, by producing a string representation

More information

61A LECTURE 14 MULTIPLE REPRESENTATIONS. Steven Tang and Eric Tzeng July 17, 2013

61A LECTURE 14 MULTIPLE REPRESENTATIONS. Steven Tang and Eric Tzeng July 17, 2013 61A LECTURE 14 MULTIPLE REPRESENTATIONS Steven Tang and Eric Tzeng July 17, 2013 Generic Functions An abstrac*on might have more than one representa*on. Python has many sequence types: tuples, ranges,

More information

CS61A Lecture 21. Amir Kamil UC Berkeley March 11, 2013

CS61A Lecture 21. Amir Kamil UC Berkeley March 11, 2013 CS61A Lecture 21 Amir Kamil UC Berkeley March 11, 2013 Announcements HW7 due on Wednesday Ants project out Looking Up Names Name expressions look up names in the environment Dot expressions look

More information

Python List built-in methods, accessing elements, selection, slicing, recursive functions, list comprehension

Python List built-in methods, accessing elements, selection, slicing, recursive functions, list comprehension ITP 20005 Programming Languages Chapter 2 Building Abstractions with Data 2.1 Introduction 2.2 Data Abstraction 2.3 Sequences List, Tuple, String, Linked List Major references: 1. Structure and Interpretation

More information

61A LECTURE 14 MULTIPLE REPRESENTATIONS

61A LECTURE 14 MULTIPLE REPRESENTATIONS 61A LECTURE 14 MULTIPLE REPRESENTATIONS Steven Tang and Eric Tzeng July 17, 2013 Generic Functions An abstrac/on might have more than one representa/on. Python has many sequence types: tuples, ranges,

More information

2.2 Data Abstraction

2.2 Data Abstraction ITP 20005 Programming Languages Chapter 2 Building Abstractions with Data 2.1 Introduction Functional Abstraction vs. Data Abstraction 2.2 Data Abstraction Example: Rational Numbers Major references: 1.

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

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

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

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

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

Class Design (Section 9 of 17)

Class Design (Section 9 of 17) the architects themselves came in to explain the advantages of both designs Class Design (Section 9 of 17) In the previous sections we have used existing classes that enable us to be able to write functions

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

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

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

More information

Object Oriented Programming #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

CS1 Lecture 3 Jan. 18, 2019

CS1 Lecture 3 Jan. 18, 2019 CS1 Lecture 3 Jan. 18, 2019 Office hours for Prof. Cremer and for TAs have been posted. Locations will change check class website regularly First homework assignment will be available Monday evening, due

More information

Programming for Engineers in Python

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

More information

>>> * *(25**0.16) *10*(25**0.16)

>>> * *(25**0.16) *10*(25**0.16) #An Interactive Session in the Python Shell. #When you type a statement in the Python Shell, #the statement is executed immediately. If the #the statement is an expression, its value is #displayed. #Lines

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

Unit Testing In Python

Unit Testing In Python Lab 13 Unit Testing In Python Lab Objective: One of the hardest parts of computer programming is ensuring that a program does what you expect it to do. For instance, a program may fail to meet specifications,

More information

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2

Announcements. Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2 61A Extra Lecture 6 Announcements Homework 1 due Monday 10/12 (today) Homework 2 released next Monday 10/19 is due 11/2 Homework 3 is to complete an extension to Project 4 Due at the same time as Project

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

PYTHON CONTENT NOTE: Almost every task is explained with an example

PYTHON CONTENT NOTE: Almost every task is explained with an example PYTHON CONTENT NOTE: Almost every task is explained with an example Introduction: 1. What is a script and program? 2. Difference between scripting and programming languages? 3. What is Python? 4. Characteristics

More information

CS1 Lecture 3 Jan. 22, 2018

CS1 Lecture 3 Jan. 22, 2018 CS1 Lecture 3 Jan. 22, 2018 Office hours for me and for TAs have been posted, locations will change check class website regularly First homework available, due Mon., 9:00am. Discussion sections tomorrow

More information

61A LECTURE 7 DATA ABSTRACTION. Steven Tang and Eric Tzeng July 3, 2013

61A LECTURE 7 DATA ABSTRACTION. Steven Tang and Eric Tzeng July 3, 2013 61A LECTURE 7 DATA ABSTRACTION Steven Tang and Eric Tzeng July 3, 2013 Announcements Trends project released later today. Due in ~2 weeks Extra midterm office hours Sunday, from noon to 6pm in 310 Soda

More information

Working with classes and objects COSC346

Working with classes and objects COSC346 Working with classes and objects COSC346 Initialisation An object should be self-contained: independent and selfsufficient Should allocate resources (memory) required for its operation Should initialise

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

Week - 01 Lecture - 04 Downloading and installing Python

Week - 01 Lecture - 04 Downloading and installing Python Programming, Data Structures and Algorithms in Python Prof. Madhavan Mukund Department of Computer Science and Engineering Indian Institute of Technology, Madras Week - 01 Lecture - 04 Downloading and

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

LECTURE 7. The Standard Library

LECTURE 7. The Standard Library LECTURE 7 The Standard Library THE STANDARD LIBRARY Python has a fantastically large standard library. Some modules are more useful than others (e.g. sys and strings). Some modules are relatively obscure.

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

Unit Tests. # Store the result of a boolean expression in a variable. >>> result = str(5)=='5'

Unit Tests. # Store the result of a boolean expression in a variable. >>> result = str(5)=='5' 7 Unit Testing Lab Objective: Finding and fixing programming errors can be difficult and time consuming, especially in large or complex programs. Unit testing is a formal strategy for finding and eliminating

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

Advanced Python Subjects. By Imri Goldberg plnnr.com

Advanced Python Subjects. By Imri Goldberg   plnnr.com Advanced Python Subjects By Imri Goldberg www.algorithm.co.il plnnr.com Introduction Many people I know come to Python from C/C++. Including me! They bring with them many unpythonic idioms: inheritance

More information

A Guide to Using Some Basic MATLAB Functions

A Guide to Using Some Basic MATLAB Functions A Guide to Using Some Basic MATLAB Functions UNC Charlotte Robert W. Cox This document provides a brief overview of some of the essential MATLAB functionality. More thorough descriptions are available

More information

EGR 111 Functions and Relational Operators

EGR 111 Functions and Relational Operators EGR 111 Functions and Relational Operators This lab is an introduction to writing your own MATLAB functions. The lab also introduces relational operators and logical operators which allows MATLAB to compare

More information

MITOCW watch?v=flgjisf3l78

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

More information

61A Lecture 16. Wednesday, October 5

61A Lecture 16. Wednesday, October 5 61A Lecture 16 Wednesday, October 5 Policy Changes Based on the Survey Homework can now be completed in pairs, if you wish. Every individual should still submit his/her own homework Please write your partner's

More information

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1

6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1 6.01, Spring Semester, 2008 Assignment 3, Issued: Tuesday, February 19 1 MASSACHVSETTS INSTITVTE OF TECHNOLOGY Department of Electrical Engineering and Computer Science 6.01 Introduction to EECS I Spring

More information

WELCOME! (download slides and.py files and follow along!) LECTURE 1

WELCOME! (download slides and.py files and follow along!) LECTURE 1 WELCOME! (download slides and.py files and follow along!) 6.0001 LECTURE 1 6.0001 LECTURE 1 1 TODAY course info what is computation python basics mathematical operations python variables and types NOTE:

More information

Modern Programming Languages. Lecture LISP Programming Language An Introduction

Modern Programming Languages. Lecture LISP Programming Language An Introduction Modern Programming Languages Lecture 18-21 LISP Programming Language An Introduction 72 Functional Programming Paradigm and LISP Functional programming is a style of programming that emphasizes the evaluation

More information

Python for C programmers

Python for C programmers Python for C programmers The basics of Python are fairly simple to learn, if you already know how another structured language (like C) works. So we will walk through these basics here. This is only intended

More information

INTERPRETATION AND SCHEME LISTS 12

INTERPRETATION AND SCHEME LISTS 12 INTERPRETATION AND SCHEME LISTS 12 COMPUTER SCIENCE 61A July 26, 2012 1 Calculator Language We are beginning to dive into the realm of interpreting computer programs. To do so, we will examine a few new

More information

61A Lecture 25. Friday, October 28

61A Lecture 25. Friday, October 28 61A Lecture 25 Friday, October 2 From Last Time: Adjoining to a Tree Set 5 9 7 3 9 7 11 1 7 11 Right! Left! Right! Stop! 5 9 7 3 9 7 11 1 7 11 2 From the Exam: Pruned Trees a b c d (a,b) (a,c) (a,d) pruned

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

INTERPRETATION AND SCHEME LISTS 12

INTERPRETATION AND SCHEME LISTS 12 INTERPRETATION AND SCHEME LISTS 12 COMPUTER SCIENCE 61A July 26, 2012 1 Calculator Language We are beginning to dive into the realm of interpreting computer programs. To do so, we will examine a few new

More information

Computer Science 21b: Structure and Interpretation of Computer Programs (Spring Term, 2004)

Computer Science 21b: Structure and Interpretation of Computer Programs (Spring Term, 2004) Computer Science 21b: Structure and Interpretation of Computer Programs (Spring Term, 2004) There are only 5 ideas in Computer Science, and by the end of this course, you ll know 3 of them --Harry Mairson

More information

CS115 - Module 4 - Compound data: structures

CS115 - Module 4 - Compound data: structures Fall 2017 Reminder: if you have not already, ensure you: Read How to Design Programs, sections 6-7, omitting 6.2, 6.6, 6.7, and 7.4. Compound data It often comes up that we wish to join several pieces

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

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

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I

ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, R E Z A S H A H I D I ENGINEERING 1020 Introduction to Computer Programming M A Y 2 6, 2 0 1 0 R E Z A S H A H I D I Today s class Constants Assignment statement Parameters and calling functions Expressions Mixed precision

More information

Programming Paradigms in Python

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

More information

Introduction to Homogeneous coordinates

Introduction to Homogeneous coordinates Last class we considered smooth translations and rotations of the camera coordinate system and the resulting motions of points in the image projection plane. These two transformations were expressed mathematically

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

Assignment 7: Due Wednesday May 11 at 6pm UPDATES on Monday May 9

Assignment 7: Due Wednesday May 11 at 6pm UPDATES on Monday May 9 CS1110 Spring 2016 Assignment 7: Due Wednesday May 11 at 6pm UPDATES on Monday May 9 You must work either on your own or with one partner. If you work with a partner, you and your partner must first register

More information

Lecture 19. Operators and Abstraction

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

More information

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types

Introduction to Computer Programming in Python Dr. William C. Bulko. Data Types Introduction to Computer Programming in Python Dr William C Bulko Data Types 2017 What is a data type? A data type is the kind of value represented by a constant or stored by a variable So far, you have

More information

Structure and Interpretation of Computer Programs

Structure and Interpretation of Computer Programs CS 61A Fall 2012 Structure and Interpretation of Computer Programs Midterm 2 Solutions INSTRUCTIONS You have 2 hours to complete the exam. The exam is closed book, closed notes, closed computer, closed

More information

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #33 Pointer Arithmetic Introduction to Programming in C Department of Computer Science and Engineering Lecture No. #33 Pointer Arithmetic In this video let me, so some cool stuff which is pointer arithmetic which helps you to

More information

Lecture 7. Memory in Python

Lecture 7. Memory in Python Lecture 7 Memory in Python Announcements For This Lecture Readings Reread Chapter 3 No reading for Thursday Lab Work on Assignment Credit when submit A Nothing else to do Assignment Moved to Fri, Sep.

More information

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today.

Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today. Lecture 6 Individual research task. You should all have completed the research task set last week. Please make sure you hand it in today. Previously Decision structures with flowcharts Boolean logic UML

More information

Math 231E, Lecture 34. Polar Coordinates and Polar Parametric Equations

Math 231E, Lecture 34. Polar Coordinates and Polar Parametric Equations Math 231E, Lecture 34. Polar Coordinates and Polar Parametric Equations 1 Definition of polar coordinates Let us first recall the definition of Cartesian coordinates: to each point in the plane we can

More information

Lecture 1. Types, Expressions, & Variables

Lecture 1. Types, Expressions, & Variables Lecture 1 Types, Expressions, & Variables About Your Instructor Director: GDIAC Game Design Initiative at Cornell Teach game design (and CS 1110 in fall) 8/29/13 Overview, Types & Expressions 2 Helping

More information

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming

Intro to Programming. Unit 7. What is Programming? What is Programming? Intro to Programming Intro to Programming Unit 7 Intro to Programming 1 What is Programming? 1. Programming Languages 2. Markup vs. Programming 1. Introduction 2. Print Statement 3. Strings 4. Types and Values 5. Math Externals

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

CS1 Lecture 5 Jan. 25, 2019

CS1 Lecture 5 Jan. 25, 2019 CS1 Lecture 5 Jan. 25, 2019 HW1 due Monday, 9:00am. Notes: Do not write all the code at once before starting to test. Take tiny steps. Write a few lines test... add a line or two test... add another line

More information

Three-address code (TAC) TDT4205 Lecture 16

Three-address code (TAC) TDT4205 Lecture 16 1 Three-address code (TAC) TDT4205 Lecture 16 2 On our way toward the bottom We have a gap to bridge: Words Grammar Source program Semantics Program should do the same thing on all of these, but they re

More information

This quiz is open book and open notes, but do not use a computer.

This quiz is open book and open notes, but do not use a computer. 1. /15 2. /10 3. /10 4. /18 5. /8 6. /13 7. /15 8. /9 9. /1 10. /1 Total /100 This quiz is open book and open notes, but do not use a computer. Please write your name on the top of each page. Answer all

More information

Lecture content. Course goals. Course Introduction. TDDA69 Data and Program Structure Introduction

Lecture content. Course goals. Course Introduction. TDDA69 Data and Program Structure Introduction Lecture content TDDA69 Data and Program Structure Introduction Cyrille Berger Course Introduction to the different Programming Paradigm The different programming paradigm Why different paradigms? Introduction

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

3D Rotations and Complex Representations. Computer Graphics CMU /15-662, Fall 2017

3D Rotations and Complex Representations. Computer Graphics CMU /15-662, Fall 2017 3D Rotations and Complex Representations Computer Graphics CMU 15-462/15-662, Fall 2017 Rotations in 3D What is a rotation, intuitively? How do you know a rotation when you see it? - length/distance is

More information

Dr Richard Greenaway

Dr Richard Greenaway SCHOOL OF PHYSICS, ASTRONOMY & MATHEMATICS 4PAM1008 MATLAB 2 Basic MATLAB Operation Dr Richard Greenaway 2 Basic MATLAB Operation 2.1 Overview 2.1.1 The Command Line In this Workshop you will learn how

More information

Long (LONGMATH) variables may be used the same as short variables. The syntax is the same. A few limitations apply (see below).

Long (LONGMATH) variables may be used the same as short variables. The syntax is the same. A few limitations apply (see below). Working with Long Numbers. Long Variables Constants You define a long variable with the LONG statement, which works similar to the DIM statement. You can define long variables and dimension long variable

More information

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013

CS61A Lecture 15. Amir Kamil UC Berkeley February 25, 2013 CS61A Lecture 15 Amir Kamil UC Berkeley February 25, 2013 Announcements HW5 due on Wednesday Trends project out Partners are required; find one in lab or on Piazza Will not work in IDLE New bug submission

More information

Intro. Classes & Inheritance

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

More information

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

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window.

Creates a 1 X 1 matrix (scalar) with a value of 1 in the column 1, row 1 position and prints the matrix aaa in the command window. EE 350L: Signals and Transforms Lab Spring 2007 Lab #1 - Introduction to MATLAB Lab Handout Matlab Software: Matlab will be the analytical tool used in the signals lab. The laboratory has network licenses

More information

Python 1: Intro! Max Dougherty Andrew Schmitt

Python 1: Intro! Max Dougherty Andrew Schmitt Python 1: Intro! Max Dougherty Andrew Schmitt Computational Thinking Two factors of programming: The conceptual solution to a problem. Solution syntax in a programming language BJC tries to isolate and

More information

CS1 Lecture 4 Jan. 23, 2019

CS1 Lecture 4 Jan. 23, 2019 CS1 Lecture 4 Jan. 23, 2019 First graded discussion sections this week yesterday/today 10 DS assignments worth 2 points each everyone gets one free 2-pointer. I.e. your lowest DS grade will be replaced

More information

Lecture 1. basic Python programs, defining functions

Lecture 1. basic Python programs, defining functions Lecture 1 basic Python programs, defining functions Lecture notes modified from CS Washington CS 142 Except where otherwise noted, this work is licensed under: http://creativecommons.org/licenses/by-nc-sa/3.0

More information

Laboratory 1 Introduction to MATLAB for Signals and Systems

Laboratory 1 Introduction to MATLAB for Signals and Systems Laboratory 1 Introduction to MATLAB for Signals and Systems INTRODUCTION to MATLAB MATLAB is a powerful computing environment for numeric computation and visualization. MATLAB is designed for ease of use

More information

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

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

More information

61A Lecture 2. Wednesday, September 4, 2013

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

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

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

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

Long (or LONGMATH ) floating-point (or integer) variables (length up to 1 million, limited by machine memory, range: approx. ±10 1,000,000.

Long (or LONGMATH ) floating-point (or integer) variables (length up to 1 million, limited by machine memory, range: approx. ±10 1,000,000. QuickCalc User Guide. Number Representation, Assignment, and Conversion Variables Constants Usage Double (or DOUBLE ) floating-point variables (approx. 16 significant digits, range: approx. ±10 308 The

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Object Oriented Programming COP3330 / CGS5409

Object Oriented Programming COP3330 / CGS5409 Object Oriented Programming COP3330 / CGS5409 Classes & Objects DDU Design Constructors Member Functions & Data Friends and member functions Const modifier Destructors Object -- an encapsulation of data

More information

OBJECT ORIENTED PROGRAMMING 5

OBJECT ORIENTED PROGRAMMING 5 OBJECT ORIENTED PROGRAMMING 5 COMPUTER SCIENCE 61A October 6, 2016 1 Object Oriented Programming In a previous lecture, you were introduced to the programming paradigm known as Object-Oriented Programming

More information

6.00 Introduction to Computer Science and Programming Fall 2008

6.00 Introduction to Computer Science and Programming Fall 2008 MIT OpenCourseWare http://ocw.mit.edu 6.00 Introduction to Computer Science and Programming Fall 2008 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

More information

EL2310 Scientific Programming

EL2310 Scientific Programming Lecture 11: Structures and Memory (yaseminb@kth.se) Overview Overview Lecture 11: Structures and Memory Structures Continued Memory Allocation Lecture 11: Structures and Memory Structures Continued Memory

More information

Chapter 11. Gauss and Karatsuba Multiplication Multiplication of complex numbers

Chapter 11. Gauss and Karatsuba Multiplication Multiplication of complex numbers Chapter 11 Gauss and Karatsuba Multiplication Copyright Oliver Serang, 2018 University of Montana Department of Computer Science 11.1 Multiplication of complex numbers As we remember from grade school,

More information

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

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

More information

Advanced Operations Research Prof. G. Srinivasan Department of Management Studies Indian Institute of Technology, Madras

Advanced Operations Research Prof. G. Srinivasan Department of Management Studies Indian Institute of Technology, Madras Advanced Operations Research Prof. G. Srinivasan Department of Management Studies Indian Institute of Technology, Madras Lecture 16 Cutting Plane Algorithm We shall continue the discussion on integer programming,

More information

Introduction to Functional Programming

Introduction to Functional Programming A Level Computer Science Introduction to Functional Programming William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims and Claims Flavour of Functional

More information

SCHEME AND CALCULATOR 5b

SCHEME AND CALCULATOR 5b SCHEME AND CALCULATOR 5b COMPUTER SCIENCE 6A July 25, 203 In the next part of the course, we will be working with the Scheme programming language. In addition to learning how to write Scheme programs,

More information

61A Lecture 7. Monday, September 16

61A Lecture 7. Monday, September 16 61A Lecture 7 Monday, September 16 Announcements Homework 2 due Tuesday at 11:59pm Project 1 due Thursday at 11:59pm Extra debugging office hours in Soda 405: Tuesday 6-8, Wednesday 6-7, Thursday 5-7 Readers

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

Public-Service Announcement

Public-Service Announcement Public-Service Announcement Hi CS 61A students! Did you know that the university has a farm? The UC Gill Tract Community Farm is located just two miles from campus and is a community space, open to all.

More information