curriculum/challenges/english/blocks/learn-special-methods-by-building-a-vector-space/666832e427d70bc5219dc62a.md
As you can see from the output, although you defined __getattr__ in your class, this method is not called yet. This happens because the default attribute access occurs through __getattribute__. Therefore, you can see the attribute value printed on the terminal.
Now modify the last two lines of code to access the z attribute of v1 in both your print() calls. This time, you are going to access an attribute that v1 does not have. As a result, __getattribute__ will raise an error and __getattr__ will be called.
You should modify your code to print the z attribute of v1 using both the dot operator and the getattr() function.
({ test: () => assert(runPython(`
n = _Node(_code)
(n.has_call("print(v1.z)") and n.has_call("print(getattr(v1, 'z'))")) or n.has_call("print(v1.z, getattr(v1, 'z'))") or n.has_call("print(getattr(v1, 'z'), v1.z)")
`)) })
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 __getattr__(self, attr):
return 'calling __getattr__'
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--
print(v1.x)
print(getattr(v1, 'x'))
--fcc-editable-region--