A
A
albertalexandrov2018-06-24 15:41:31
Python
albertalexandrov, 2018-06-24 15:41:31

How to return a float from len()?

Hello!
The task is to return the length of a vector using the len() function. The vector class is initialized with x and y coordinates.

class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __len__(self):
        return math.sqrt(self.x**2 + self.y**2)  # TypeError: 'float' object cannot be interpreted as an integer

Exercise:
Implement a class of 2-dimensional vectors Vec2d — define the basic mathematical operations: sum Vec2d.__add__, difference Vec2d.__sub__, multiplication by a scalar and scalar multiplication (Vec2d.__mul__); add the ability to calculate the length of the vector a through len(a); add the int_pair method to get a pair (tuple) of integers.

The len() function returns an int. How to return a float?
PS This is from the course on the course.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Burov, 2018-06-24
@BuriK666

Don't confuse len and vector length
You need to implement method overloading, more details:
https://stackoverflow.com/questions/7642434/is-the...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question