Lecture 21
String representation and Special Methods
mic
String Representations
String Representations
String Representations
In Python, all objects produce two string representations:
String Representations
In Python, all objects produce two string representations:
The str and repr strings are often the same, but not always
What is easier to understand?
The repr String for an Object
The result of calling repr on a value is what Python prints in an interactive session
The repr String for an Object
The result of calling repr on a value is what Python prints in an interactive session
The repr String for an Object
The result of calling repr on a value is what Python prints in an interactive session
The repr String for an Object
The result of calling repr on a value is what Python prints in an interactive session
Some objects do not have a simple Python-readable string
The repr String for an Object
The result of calling repr on a value is what Python prints in an interactive session
Some objects do not have a simple Python-readable string
The repr function returns a Python expression (a string) that evaluates to an equal object: https://docs.python.org/3/library/functions.html#repr
eval( ):
utility which lets a Python program run Python code within itself, by evaluating expressions.
eval(expression, globals=None, locals=None)
(quick demo)
The repr String for an Object
The repr function returns a Python expression (a string) that evaluates to an equal object: https://docs.python.org/3/library/functions.html#repr
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise...
The repr String for an Object
The repr function returns a Python expression (a string) that evaluates to an equal object: https://docs.python.org/3/library/functions.html#repr
Return a string containing a printable representation of an object. For many types, this function makes an attempt to return a string that would yield an object with the same value when passed to eval(), otherwise
The str String for an Object, Demo
The str String for an Object
The str String for an Object + another Demo
The result of calling str on the value of an expression is what Python prints using the print function:
Question: Output?
name = “ ‘ Marina ‘ ”
eval(name) eval(repr(name)) str(name)
A: ‘ Marina ’ ‘ Marina ’ \” “ ‘ Marina ‘ “ \”
B: Error “ ‘ Marina ‘ “ ‘ Marina ’
C: Marina Error ‘ Marina’
D: “ ‘ Marina ‘ “ ‘ Marina ’ “ ‘ Marina ‘ “
E: ‘ Marina ‘ “ ‘ Marina ‘ “ “ ‘ Marina ‘ “
Question
class Animal:
voice = lambda: "Grrrr"
def __init__(self, type, sound):
self.type = type
self.voice = lambda: sound
a = Animal("dog", "woof-woof")
A: a.voice()
Animal.voice()
B: Animal.voice()
a.voice()
C: a.voice(“woof-woof”)
Animal.voice(“Grrrrr”)
D: Animal.voice(“woof-woof”)
a.voice(“Grrrrr”)
E: Not possible
Desired output:
woof-woof
Grrrr
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:
User defined classes
class Test():
def __init__(self, n):
self.n = n
def __str__(self):
return 'this is me: ' + str(self.n)
def __repr__(self):
return 'this is a repr'
>>> t = Test(5)
>>> t
this is a repr
>>> print(t)
this is me: 5
User defined classes
class Test():
def __init__(self, n):
self.n = n
def __str__(self):
return 'this is me: ' + str(self.n)
def __repr__(self):
return 'this is a repr'
>>> t = Test(5)
>>> t.__repr__()
‘this is a repr’
>>> t.__str__()
‘this is me: 5’
User defined classes
class Test():
def __init__(self, n):
self.n = n
def __repr__(self):
return 'this is a repr'
>>> t = Test(5)
>>> t
this is a repr
>>> print(t)
this is a repr
User defined classes
class Test():
def __init__(self, n):
self.n = n
>>> t = Test(5)
>>> t
<__main__.Test object at 0x7fd1d8096430>
>>> print(t)
<__main__.Test object at 0x7fd1d8096430>
mic
Recap
Recap
class Ratio:
def __init__(self, n, d):
self.numer = n
self.denom = d
Recap
class Ratio:
def __init__(self, n, d):
self.numer = n
self.denom = d
def __str__(self):
return '{0}/{1}'.format(self.numer, self.denom)
Recap
class Ratio:
def __init__(self, n, d):
self.numer = n
self.denom = d
def __str__(self):
return '{0}/{1}'.format(self.numer, self.denom)
def __repr__(self):
return 'Ratio({0}, {1})'.format(self.numer, self.denom)
Recap
class Ratio:
def __init__(self, n, d):
self.numer = n
self.denom = d
def __str__(self):
return '{0}/{1}'.format(self.numer, self.denom)
def __repr__(self):
return 'Ratio({0}, {1})'.format(self.numer, self.denom)
>>> frac1 = Ratio(3, 4)
>>> print(frac1)
3/4
>>> frac1
Ratio(3, 4)
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:
repr asks an argument to display itself
invokes a zero-argument method __repr__ on its argument
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:
repr invokes a zero-argument method __repr__ on its argument
str invokes a zero-argument method __str__ on its argument
Special Method Names
Special Method Names in Python
Certain names are special because they have built-in behavior. Always start and end with two underscores
Special Method Names in Python
Certain names are special because they have built-in behavior. Always start and end with two underscores
Special Method Names in Python
Certain names are special because they have built-in behavior. Always start and end with two underscores
Demo about + Example: https://www.python-course.eu/python3_magic_methods.php
Example for __add__
Special Methods:
Adding instances of user-defined classes invokes either the __add__ or __radd__ method
Special Methods: demo
Adding instances of user-defined classes invokes either the __add__ or __radd__ method
http://getpython3.com/diveintopython3/special-method-names.html
https://docs.python.org/3/reference/datamodel.html#special-method-names
__radd__ = __add__ line
class Student:
def __init__(self, age):
self.age = age
def __lt__(self, anoter_Student):
if self.age<anoter_Student.age:
return True
s1 = Student(20)
s2 = Student(22)
print(s1<s2)
Answers:
A: True
B: False
C: None
D: <.... >
E: Something else
class Student:
def __init__(self, age):
self.age = age
def __lt__(self, anoter_Student):
if self.age<anoter_Student.age:
return True
s1 = Student(22)
s2 = Student(20)
print(s1<s2)
Answers:
A: True
B: False
C: None
D: <.... >
E: Something else
class Student:
def __init__(self, age):
self.age = age
def __lt__(self, anoter_Student):
if self.age<anoter_Student.age:
return True
s1 = Student(20)
s2 = Student(22)
#print(s1<s2) # it is true
print(s2>s1)
True
Why?
class Student:
def __init__(self, age):
self.age = age
def __lt__(self, anoter_Student):
if self.age<anoter_Student.age:
return True
s1 = Student(20)
s2 = Student(22)
#print(s1<s2)
print(s2>s1)
class Student:
def __init__(self, age):
self.age = age
def __lt__(self, anoter_Student):
if self.age<anoter_Student.age:
return True
def __eq__(self, anoter_Student):
if self.age == anoter_Student.age:
return True
else:
return False
s1 = Student(20)
s2 = Student(22)
print(s1==s2) <--False
print(s1!=s2) <--True
Implementing str
and
repr
Checking your understanding!
class Check:
num = 10
def question(self):
print(self.num)
def setter(self, number):
self.num = number
A: 10� 10
B: None
C: Something Else
D: Error
obj1 = Check()
obj2 = Check()
obj1.question()
obj2.question()
Checking your understanding!
class Check:
num = 10
def question(self):
print(self.num)
def setter(self, number):
self.num = number
A: 10� 10
B: None
C: Something Else
D: Error
obj1 = Check()
obj2 = Check()
obj1.setter(17)
obj1.question()
obj2.question()
Checking your understanding!
class Check:
num = 10
def question(self):
print(Check.num)
def setter(self, number):
self.num = number
A: 10� 10
B: None
C: Something Else
D: Error
obj1 = Check()
obj2 = Check()
obj1.setter(17)
obj1.question()
obj2.question()
Implementing repr and str
The behavior of repr is slightly more complicated than invoking __repr__ on its argument:
How would we implement this behavior? Which of the following function definitions corresponds to a function repr that takes in some argument, looks up the class attribute called __repr__ and invokes it?
A: D:
B: E:
C:
Implementing repr and str
The behavior of str is also complicated:
Question: How do we understand this behavior?
(demo)
What will be printed?
class UC(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "UC('" + self.name + "')"
def __str__(self):
return 'UC ' + self.name
ucsd = UC("San Diego")
print(repr(ucsd))
A: UC San Diego
B: "UC('San Diego')"
C: UC('San Diego')
class UC(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "UC('" + self.name + "')"
def __str__(self):
return 'UC ' + self.name
ucsd = UC("San Diego")
print(str(ucsd))
A: UC San Diego
B: 'UC('San Diego')'
C: UC('San Diego')
class UC(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "UC('" + self.name + "')"
def __str__(self):
return 'UC ' + self.name
ucsd = UC("San Diego")
print(ucsd.__repr__())
A: UC San Diego
B: 'UC('San Diego')'
C: UC('San Diego')
class UC(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "UC('" + self.name + "')"
def __str__(self):
return 'UC ' + self.name
ucsd = UC("San Diego")
repr(str(ucsd)) == repr(ucsd.__str__())
A: True
B: False
class UC(object):
def __init__(self, name):
self.name = name
def __repr__(self):
return "UC('" + self.name + "')"
def __str__(self):
return 'UC ' + self.name
ucsd = UC("San Diego")
print(ucsd.__str__())
A: UC San Diego
B: 'UC('San Diego')'
C: UC('San Diego')