20 Representation 1pp
20 Representation 1pp
Announcements
String Representations
String Representations
An object value should behave like the kind of data it is meant to represent
The str and repr strings are often the same, but not always
4
The repr String for an Object
The repr function returns a Python expression (a string) that evaluates to an equal 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
>>> repr(min)
'<built-in function min>'
5
The str String for an Object
The result of calling str on the value of an expression is what Python prints
using the print function:
>>> print(half)
1/2
(Demo)
6
F-Strings
String Interpolation in Python
8
Polymorphic Functions
Polymorphic Functions
Polymorphic function: A function that applies to many (poly) different forms (morph) of data
str and repr are both polymorphic; they apply to any object
>>> half.__repr__()
'Fraction(1, 2)'
>>> half.__str__()
'1/2'
10
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?
def repr(x):
return x.__repr__(x)
The behavior of str is also complicated:
• An instance attribute called __str__ is ignored def repr(x):
return x.__repr__()
• If no __str__ attribute is found, uses repr string
• (By the way, str is a class, not a function) def repr(x):
• Question: How would we implement this behavior? return type(x).__repr__(x)
def repr(x):
return type(x).__repr__()
def repr(x):
(Demo) return super(x).__repr__()
11
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-interpretable and
human-readable strings implement an interface for producing string representations
(Demo)
12
Special Method Names
Special Method Names in Python
14
Special Methods
Adding instances of user-defined classes invokes either the __add__ or __radd__ method
http://getpython3.com/diveintopython3/special-method-names.html
http://docs.python.org/py3k/reference/datamodel.html#special-method-names
(Demo)
15
Generic Functions
>>> Ratio(1, 3) + 1
Ratio(4, 3)
>>> 1 + Ratio(1, 3)
Ratio(4, 3)
(Demo)
16