__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.
Remember that, in classes, methods defined in the body of the class have the keyword
selfas 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
selfwill be absolutely necessary for our implementation of these special methods
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
assertto 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
Have your teacher walk you through this one as well
Write a class called
PolarCoordinatesthat will take a value called
radiusand 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.
Write a modified version of the
Matrixclass(that was defined in one of the example problems in this section) so that the
__str__method instead returns a string containing a single number: the matrix’s Frobenius norm. The formula for the Frobenius norm will be the square root of the sum of all the elements squared in the matrix. Also, the unmodified
Matrixclass code will be given.
Write a class called
Linewhich will take the arguments
interceptin its constructor. When we print the class, the
__str__method should return a string with the line expressed in the form y=mx+b where m and b are the slope and intercept respectively.