Printing variables using user defined classes - requiring attribute to print

Mission-Screen Link: https://app.dataquest.io/m/352/object-oriented-python/10/creating-and-updating-an-attribute

class NewList(DQ):
#     """
#     A Python list with some extras!
#     """
    def __init__(self, initial_state):
        self.data = initial_state
        self.calc_length()
        
    
    def append(self, new_item):
#         """
#         Append `new_item` to the NewList
#         """
        self.data = self.data + [new_item]
        self.calc_length()
    
    def calc_length(self):
        length = 0
        for item in self.data:
            length += 1
        self.length = length

fibonacci = NewList([1, 1, 2, 3, 5])
print(fibonacci.data)
print(fibonacci.length)
print('\n')
fibonacci.append(8)
**print(fibonacci)**
print(fibonacci.length)

What I expected to happen:

Along with the original and updated lengths I expected to print the updated contents of the variable fibonacci as [1, 1, 2, 3, 5, 8]

What actually happened:

Instead of the value of the variable ‘fibonacci’ the following was printed:

Class Name:       <class '__main__.NewList'>
Class Attributes: {'data': [1, 1, 2, 3, 5, 8], 'length': 6}
Class Methods:    ['append', 'calc_length']

Other details:

Had to use the code print(fibonacci.data) to print the contents of the variable as [1, 1, 2, 3, 5, 8]

Attributes are not required for in-built classes such as str, int etc so just wondering why the difference?

1 Like

Hi @mattrosinski,

Class Name:       <class '__main__.NewList'>
Class Attributes: {'data': [1, 1, 2, 3, 5, 8], 'length': 6}
Class Methods:    ['append', 'calc_length']

is displayed because you are printing the object:

print(fibonacci)

The output you are receiving is a representation of the object. Which is equivalent to running:

print(repr(fibonacci))

To change the representation of the object, you have to add a __repr__ method to your class like this:

def __repr__(self):
        return str(self.data)

Full Code:

class NewList(DQ):
    """
    A Python list with some extras!
    """
    def __init__(self, initial_state):
        self.data = initial_state
        self.calc_length()
        
    def __repr__(self):
        return str(self.data)
    
    def calc_length(self):
        """
        A helper function to calculate the .length
        attribute.
        """
        length = 0
        for item in self.data:
            length += 1
        self.length = length
    
    def append(self, new_item):
        """
        Append `new_item` to the NewList
        """
        self.data = self.data + [new_item]
        self.calc_length()

fibonacci = NewList([1, 1, 2, 3, 5])
print(fibonacci)

fibonacci.append(8)
print(fibonacci)

Output:

[1, 1, 2, 3, 5]
[1, 1, 2, 3, 5, 8]

You can read more about this method here:
https://docs.python.org/3/reference/datamodel.html#object.repr

Hope this helps :slightly_smiling_face:

Best,
Sahil

1 Like