0

How to perform the below:

def to_distance(speed, time):
    return speed * time

speed = 10.0
to_distance(speed, 5)

in the context of a class. That is, using a class with a base class of int and having a to_distance method. The below attempt:

class Speed(float):

    def __init__(self, n):
        super().__init__(n)

    def to_distance(self, n):
        return self * n

running:

s = Speed(11.0)

results in a TypeError:

TypeError                                 Traceback (most recent call last)
<ipython-input-18-4c35f2c0bca9> in <module>
----> 1 s = Speed(11.0)

<ipython-input-17-6baa46f60665> in __init__(self, n)
      2 
      3     def __init__(self, n):
----> 4         super().__init__(n)
      5 
      6     def to_distance(self, n):

TypeError: object.__init__() takes no arguments
Greg
  • 8,175
  • 16
  • 72
  • 125
  • This error is because you called `super.__init__` instead of `super().__init__`. However, you can't pass a value either way. Perhaps just save `self.n = n` in `__init__`? – Nathan Apr 12 '19 at 05:35
  • @Nathan good pick up, oversight which I corrected, albeit the challenge still persists – Greg Apr 12 '19 at 05:38

2 Answers2

1

Even this seems to work, though I'm a bit confused - maybe somebody with better knowledge of Python internals can chime in?

class Speed(float):
    def __init__(self, n):
        super().__init__()

    def to_distance(self, n):
        return self * n

s = Speed(2)
print(s) # 2.0
print(isinstance(s, float)) # True
print(s ** 2) # 4.0
z = s - 2
print(isinstance(z, Speed)) # False
print(isinstance(z, float)) # True
print(s.to_distance(3)) # 6.0

EDIT - adding print(self, n) to __init__ gives 2.0 2 when calling s = Speed(2). What I think is happening is that __new__ has already made self into the appropriate value, so n isn't needed anymore at __init__. Removing super().__init__() leads to just the same results above, so we could just have this instead:

class Speed(float):
    def to_distance(self, n):
        return self * n

EDIT2 - you might want to take a look at this question.

Nathan
  • 9,651
  • 4
  • 45
  • 65
0

you can try this:

class Speed(float):
    def __init__(self, n):
        float.__init__(n)

    def to_distance(self, n):
        return self * n

test and output:

s = Speed(11.0)
dist = s.to_distance(5)
print(dist)   # output 55.0
recnac
  • 3,744
  • 6
  • 24
  • 46