When implementing the __repr__() method, do all object attributes have to be used when constructing the string?
Answer
While you are allowed to include or exclude any information from the object that you want, the Python documentation recommends that the implementation for __repr__() should contain as much information as possible and if, at all possible, it should contain whatever is necessary to recreate the object. The __str__() method also returns a string representing the object but it can be used for a more informal representation of the object.
In a sense, instance.__repr__() is a getter, only it gets everything, and the expected return value will be a string representation of the data points of the instance as initialized and or modified.
The operative phrase above was return value. Getters don’t do things; they return things.
A function’s parameters are names that are local to that function. When the function completes its execution, the local variables are lost. Therefore, if we wish to preserve the values of the function parameters, we need to save those values somewhere, for example, in instance variables, which are not merely local to the function.
An instance variable does not necessarily need to have the same name as a parameter that is used to set its value.
We don’t necessarily always need to save the value of a parameter exactly as it was given.
See the following:
class Circle:
pi = 3.14149265
def __init__(self, circumference):
self.radius = circumference / Circle.pi
def get_circumference(self):
return self.radius * Circle.pi
def get_radius(self):
return self.radius
c = Circle(10.0)
print(c.get_circumference())
print(c.get_radius())
Output:
10.0
3.183200189884258
We instantiated the Circle with the circumference, but calculated its radius and saved that value. In a sense, we discarded the value provided by the argument, but we can use the saved radius to recover an approximation of the circumference. Admittedly, we could lose some precision in the process.
The guiding principle is that we use parameters of the __init__ method to provide information that is needed to instantiate an instance. We might even use some of that information to perform other tasks related to the context in which the instance was created, such as maintaining files, or coordination with other objects. However, in some cases, we might not need to retrieve the provided information later, exactly as it was given originally.
is_hungry is a variable that can store Bool value. It can either be True or False. “is_hungry” is a descriptive term used to help communicate that a Bool value goes there.