Back to Freecodecamp

Step 9

curriculum/challenges/english/blocks/learn-special-methods-by-building-a-vector-space/65f3fa097f26b510db6c710b.md

latest1.2 KB
Original Source

--description--

Great, norm is working as expected. Now, if you try to print v1, you'll get the default string representation of an object (something like <__main__.Vector object at 0x11eb778>).

Inside the Vector class, declare an empty __str__ method to implement a readable string representation. Remember to give it a self parameter.

Pay attention to not print v1 until __str__ returns a string, otherwise you'll get a TypeError, because __str__ must always return a string.

--hints--

You should define a __str__ method within the Vector class.

js
({
    test: () => assert(runPython(`
      _Node(_code).find_class("Vector").has_function("__str__")
    `))
})

Your __str__ method should have a self parameter.

js
({
    test: () => assert(runPython(`
      _Node(_code).find_class("Vector").find_function("__str__").has_args("self")
    `))
})

--seed--

--seed-contents--

py
--fcc-editable-region--
class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        
    def norm(self):
        return (self.x**2 + self.y**2)**0.5

v1 = Vector(2, 3)
print(v1.norm())
--fcc-editable-region--