ITP 20005 Programming Languages Chapter 2 Building...
Transcript of ITP 20005 Programming Languages Chapter 2 Building...
ITP 20005 Programming LanguagesChapter 2 Building Abstractions with Data
2.5 Object-Oriented Programming1. Polymorphism – repr, str2. Interface3. @property4. Example – Complex number
Major references: 1. Structure and Interpretation of Computer Programs(SICP) by Abelson and Sussman, MIT
Composing Programs by John DeNero, Google2. MITx OPENCOURSEWARE(OCW) 6.00 SC Lecture 3. UC Berkley CS61A Lecture 4. Python, Wikipedia and many on-line resources.Prof. Youngsup Kim, [email protected], 2014 Programming Languages, CSEE Dept., Handong Global University
………may be thoroughly equipped for every good work.
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 Abstraction
• String Representations
Object-Oriented Programming
5
An object value should behave like the kind of data it is meant to represent.
String Representations
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.
6
The repr function returns a Python expression (a string) that evaluates to an equal object.
The repr String for an 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.
>>> 12e12
12000000000000.0
>>> print(repr(12e12))
12000000000000.0
Some objects do not have a simple Python-readable string.
>>> repr(min)
'<built-in function min>'
7
Human interpretable strings are useful as well:
The str String for an Object
>>> import datetime
>>> today = datetime.date(2014, 11, 20)
>>> repr(today)
'datetime.date(2014, 11, 20)'
>>> str(today)
'2014-11-20'
>>> print(today)
2014-11-20
The result of calling str on the value of an expression is what Python printsusing the print function:
8
The str String for an Object
>>> 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)
2014-11-20
>>> print(str(today))
2014-11-20
>>> str(today)
'2014-11-20'
(Demo)
9
Object Abstraction
• String Representations
Object-Oriented Programming
• Polymorphic Functions
10
A function that applies to many (poly) different forms (morph) of data.
Polymorphic Functions
>>> today.__str__()
'2014-11-20'
str invokes a zero-argument method __str__ on its argument.
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)'
11
The behavior of repr is slightly more complicated than invoking __repr__ on its argument:
Implementing repr and str
The behavior of str is also complicated:
• An instance attribute called __repr__ is ignored! Only class attributes are found.
• Question: How would we implement this behavior?
• 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]
12
Demo
class Bear:
def __repr__(self):
return 'Bear()'
>>> Bear()
Bear()
>>> oski = Bear()
>>> oski.__repr__()
'Bear()'
>>> oski
Bear()
>>>
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()
>>>
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
>>>
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__())
>>> 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
defining instance methods: __repr__, __str__
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)
This implementation works exactly how the Python interpreter evaluates.
>>> print_bear()
a bear
a bear
Bear()
oski
this bear instance
>>>
17
Object Abstraction
• String Representations
Object-Oriented Programming
• Polymorphic Functions
• Interfaces
18
Message passing:
Interfaces
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.
Classes that implement __repr__ and __str__ methods that return Python- and human-readable strings implement an interface for producing string representations.
Example:
19
Object Abstraction
• String Representations
Object-Oriented Programming
• Polymorphic Functions
• Property Methods
20
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 5
4
3
No method calls!
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
4
3
No method calls!
5
2
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
4
3
No method calls!
5
2
23
Property Methods
Often, we want the value of instance attributes to stay in sync.
The @property decorator on a method designates that it will be called whenever it islooked up on an instance.
>>> 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!
4
3
5
2
24
Property Methods
Often, we want the value of instance attributes to stay in sync.
The @property decorator on a method designates that it will be called whenever it islooked up on an instance.
>>> 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!
4
3
5
2
It allows zero-argument methods to be called without an explicit call expression.
[Demo]
Attribute acts like a method!
25
Property Methods [Demo]
# Rational numbersclass Rational:
"""A mutable fraction."""def __init__(self, n, denom):
self.numer = nself.denom = denom
def __repr__(self):return 'Rational({0}, {1})'.format(self.numer,
self.denom)
26
Property Methods [Demo]
# Rational numbersclass Rational:
"""A mutable fraction."""def __init__(self, n, denom):
self.numer = nself.denom = denom
def __repr__(self):return 'Rational({0}, {1})'.format(self.numer,
self.denom)>>> Rational(1, 2)
Rational(1, 2)
27
Property Methods [Demo]
# Rational numbersclass Rational:
"""A mutable fraction."""def __init__(self, n, denom):
self.numer = nself.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
28
Property Methods [Demo]
# Rational numbersclass Rational:
"""A mutable fraction."""def __init__(self, n, denom):
self.numer = nself.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()
0.6
29
Property Methods [Demo]
# Rational numbersclass Rational:
"""A mutable fraction."""def __init__(self, n, denom):
self.numer = nself.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)
@propertydef float_value(self):
return self.numer/self.denom >>> x = Rational(3, 5)
>>> x.float_value
0.6
>>> x.numer = 4
>>> x.float_value
0.8
30
Formatting Strings with the format() Method and %s
>>> '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.'
• 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.'
31
Formatting Strings with the format() Method and %s
The general syntax for a format placeholder is
%[flags][width][.precision]type
32
Object Abstraction
• String Representations
Object-Oriented Programming
• Polymorphic Functions
• Property Methods
Example: Complex Number
• Property Methods• Interfaces
33
Multiple Representations of Abstract Data
Most programs don't care about the representation.
Some arithmetic operations are easier using one representation than the other.
Rectangular and polar representations for complex numbers
34
Implementing Complex Arithmetic
Assume that there are two different classes that both represent Complex numbers.
Number Rectangular representation Polar representation
1 + −1 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)
35
Complex Arithmetic Abstraction Barriers
Parts of the program that... Treat complex numbers as... Using...
Use complex numbersto perform computation
whole data valuesx.add(y),
x.mul(y)
Add complex numbers real and imaginary partsreal, imag,
ComplexRI
Multiply complex numbers magnitudes and anglesmagnitude, angle,
ComplexMA
Implementation of the Python object system
36
Object Abstraction
• String Representations
Object-Oriented Programming
• Polymorphic Functions
• Property Methods
Example: Complex Number
• Implementation
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]
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
ComplexRI ComplexMA
[Demo]
What is called in OOP?
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
[Demo]
What is called in OOP?
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)
41
The Rectangular Representation
class ComplexRI(Complex):
"""A rectangluar representation of a complex number."""
def __init__(self, real, imag):
self.real = real
self.imag = imag
@property
def magnitude(self):
return (self.real ** 2 + self.imag ** 2) ** 0.5
@property
def angle(self):
return atan2(self.imag, self.real)
def __repr__(self):
return 'ComplexRI({0}, {1})'.format(self.real, self.imag)
The @property decorator allows zero-argument methods to be called without the standard call expression syntax, so that they appear to be simple attributes.
Property decorator: "Call this function on attribute look-up"
math.atan2(y,x): Angle betweenx-axis and the point(x,y)
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)
43
The Polar Representation
class ComplexMA(Complex):
"""A polar represenation of a complex number"""
def __init__(self, magnitude, angle):
self.magnitude = magnitude
self.angle = angle
@property
def real(self):
return self.magnitude * cos(self.angle)
@property
def imag(self):
return self.magnitude * sin(self.angle)
def __repr__(self):
return 'ComplexMA({0}, {1})'.format(self.magnitude,
self.angle)
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, 3.141592653489793
>>> x = i.mul(i)
>>> x.real
-1.0
>>> x.imag
1.2246467991473532e-16
>>> round(x.imag)
0
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(1.0000000000000002, 4.0)
>>> ComplexRI(0, 1).mul(ComplexRI(0, 1))
1 + 4 −1
ComplexRI(0, 2)
ComplexMA(0, pi/2)
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(1.0000000000000002, 4.0)
>>> ComplexRI(0, 1).mul(ComplexRI(0, 1))
1 + 4 −1
ComplexRI(0, 2)
ComplexMA(0, pi/2)
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(1.0000000000000002, 4.0)
>>> ComplexRI(0, 1).mul(ComplexRI(0, 1))
ComplexMA(1.0, 3.141592653589793)
1 + 4 −1
ComplexRI(0, 2)
ComplexMA(0, pi/2)
−1
ITP 20005 Programming LanguagesChapter 2 Building Abstractions with Data
2.5 Object-Oriented Programming1. Polymorphism – repr, str2. Interface3. @property4. 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, Google2. MITx OPENCOURSEWARE(OCW) 6.00 SC Lecture 3. UC Berkley CS61A Lecture 4. Python, Wikipedia and many on-line resources.Prof. Youngsup Kim, [email protected], 2014 Programming Languages, CSEE Dept., Handong Global University