__str__ returns the class object formatted as a string (in a readable format). The return type is a string.
__init__ constructs an instance of the class object given some values. The return type is the class itself.
Refresher:
Remember that, in classes, methods defined in the body of the class have the keyword self as their first argument. This is a special argument that allows us to reference variables stored in the object as well as other methods in the class. It is also used to create variables (aka "fields" or "attributes") that store the unique contents of the class. Our usage of self will be absolutely necessary for our implementation of these special methods
Example:
class Vector:
def __init__(self, vals):
"""
This is the constructor
Arguments:
self - a reference to the object we are creating
vals - a list of integers that are the contents of our vector
"""
self.vals = vals # we're using the self keyword to create a
# field, property, or attribute of the class
def __str__(self):
"""
String Function
Converts the object to a string in readable format for
programmers
"""
return str(self.vals) # return the contents of the vector
vec = Vector([2, 3, 2])
print(str(vec)) # would print [2, 3, 2]
View code on GitHub.
Have your teacher walk you through this one
Build a class called Matrix that takes a list of lists (containing integers) and store it as a field. Add an assertion using assert to ensure that the list of lists is rectangular (i.e. assert len(list_0) = len(list_i) for i in range(n)). You should also implement a __str__ method so that we can print the contents of the matrix using print without having to access its field
💻 Template code
✅ Solution code
Have your teacher walk you through this one as well
Write a class called PolarCoordinates that will take a value called radius and a value called angle. When we print this class, we want the coordinates in Cartesian coordinates, or we want you to print two values: x and y. (If you don't know the conversion formula, x = radius * cos(angle), y = radius * sin(angle). Use Python's built-in math library for the cosine and sine operators. More on Polar vs Cartesian coordinates can be found here.
💻 Template code
✅ Solution code