Back to Freecodecamp

Step 34

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

latest1.4 KB
Original Source

--description--

Now, print the result of accessing the x attribute of v1 both with the dot operator and the getattr() built-in function.

You will see that __getattribute__ is called in both cases.

--hints--

You should print the x attribute of v1 using both the dot operator and the getattr() function.

js
({ test: () => assert(runPython(`
n = _Node(_code)
(n.has_call("print(v1.x)") and n.has_call("print(getattr(v1, 'x'))")) or n.has_call("print(v1.x, getattr(v1, 'x'))") or n.has_call("print(getattr(v1, 'x'), v1.x)")
`)) })

--seed--

--seed-contents--

py
class R2Vector:
    def __init__(self, *, x, y):
        self.x = x
        self.y = y

    def norm(self):
        return sum(val**2 for val in vars(self).values())**0.5

    def __str__(self):
        return str(tuple(getattr(self, i) for i in vars(self)))

    def __repr__(self):
        arg_list = [f'{key}={val}' for key, val in vars(self).items()]
        args = ', '.join(arg_list)
        return f'{self.__class__.__name__}({args})'
    
    def __getattribute__(self, attr):                
        return 'calling __getattribute__'

class R3Vector(R2Vector):
    def __init__(self, *, x, y, z):
        super().__init__(x=x, y=y)
        self.z = z

v1 = R2Vector(x=2, y=3)
v2 = R3Vector(x=2, y=2, z=3)
# print(f'v1 = {v1}', f'\nrepr = {repr(v1)}')
# print(f'v2 = {v2}', f'\nrepr = {repr(v2)}')
--fcc-editable-region--

--fcc-editable-region--