如何正确地将float用作基类并为新类定义方法?

时间:2019-04-12 05:31:42

标签: python python-3.x class inheritance base-class

如何执行以下操作:

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

speed = 10.0
to_distance(speed, 5)

在类的上下文中。也就是说,使用具有int基类并具有to_distance方法的类。下面的尝试:

class Speed(float):

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

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

运行:

s = Speed(11.0)

得到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

2 个答案:

答案 0 :(得分:1)

即使这似乎行得通,尽管我有点困惑-也许有人对Python内部知识有更深入的了解?

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

编辑-在调用print(self, n)时将__init__添加到2.0 2会得到s = Speed(2)。我认为正在发生的事情是__new__已经使self成为适当的值,因此n不再需要__init__。删除super().__init__()会得到与上面相同的结果,因此我们可以改成这样:

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

EDIT2-您可能想看看this question

答案 1 :(得分:0)

您可以尝试以下操作:

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

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

测试并输出:

s = Speed(11.0)
dist = s.to_distance(5)
print(dist)   # output 55.0