Back to Freecodecamp

Step 23

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

latest1.7 KB
Original Source

--description--

When you need to dynamically access some attributes starting from a string input, the built-in getattr() function is what you need. It takes an object as its first argument, and a string containing the attribute name as its second attribute.

Start to fix the __str__ method by replacing the string returned by __str__() with a generator expression that iterates through the object attributes and calls getattr() for each attribute i.

--hints--

You should return a generator expression that iterates over vars(self).

js
({ test: () => assert(runPython(`_Node(_code).find_class("R2Vector").find_function("__str__").find_return().find_comp_iters()[0].is_equivalent("vars(self)")`)) })

You should return a generator expression that uses i as the iteration variable.

js
({ test: () => assert(runPython(`_Node(_code).find_class("R2Vector").find_function("__str__").find_return().find_comp_targets()[0].is_equivalent("i")`)) })

You should return a generator expression that calls getattr(self, i) for each item i in vars(self).

js
({ test: () => assert(runPython(`_Node(_code).find_class("R2Vector").find_function("__str__").find_return().find_comp_expr().is_equivalent("getattr(self, i)")`)) })

--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
--fcc-editable-region--
    def __str__(self):
        return f'{self.x, self.y}'
--fcc-editable-region--
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(v1.norm())
print(v2.norm())