Lesson Notes
Fstrings in Python allow you to easily use variables in a string
Without fstrings
num = 5
t = range(10)
mystr = "This is a string with a " + str(num) + " and " + str(t)
print(mystr)
with fstrings
num = 5
t = range(10)
mystr = f"This is a string with a {num} and {t}"
print(mystr)
print(f"This is another fstring: {1 > 0}")
{``}
f
at the beginning of the stringHow is Python converting binary data to a string?
var = 2
print(var)
2 = binary value ...0010
Python uses __dunders__
to manipulate object data. Any method surrounded by __
is referered to as a dunder in python.
Dunders are used by Python, not by the programmers. In the same way someone wrote print()
for you to use, you can write dunders for Python to use.
Most dunder methods have a default implementaion that you can override. For example, __init__
is optional because it has already been implemented for you as an empty method:
class Num:
def __init__(self):
pass
class Num:
def __init__(self):
self.num = 5
n = Num()
print(n)
print(n.num)
The __str__
dunder allows you to overwrite what prints when you print your object
__str__
must return a string objectself
DON'T:
__str__
method__str__
explicitly,
str(var)
f'{var}'
__str__
class Num:
def __init__(self, x = 0):
self.num = x
def __str__(self):
return str(self.num)
n = Num(9)
print(n)
__str__
class Point:
def __init__(self, x=0, y=0, color="red"):
self.x = x
self.y = y
if color == "green":
print("You are a bad person")
color = "blue"
self.color = color
def set_to_complimentary_color(self):
red_comp = 255- self.color[0]
blue_comp = 255- self.color[1]
green_comp = 255- self.color[2]
self.color = [red_comp, blue_comp, green_comp]
class Graph:
def __init__(self, title="My Graph"):
self.points = []
self.title = title
def add_point(self, p):
self.points.append(p)
def __str__(self):
graph_str = ""
#...
return graph_str
def main():
g = Graph()
print(g)
p = Point(5, 2)
p2 = Point(3,4)
g.add_point(p)
g.add_point(p2)
print(g)
main()
Try writing the
__str__
method for theGraph
class...
def __str__(self):
points_list = []
for p in self.points:
points_list.append(f’({p.x}, {p.y})')
return ", ".join(points)