Python 如何正确使用float作为基类,并为新类定义方法?
如何执行以下操作:Python 如何正确使用float作为基类,并为新类定义方法?,python,python-3.x,class,inheritance,base-class,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,
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 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
TypeError回溯(最近一次调用)
在里面
---->1s=速度(11.0)
in_uuuinit_uuu(self,n)
2.
3定义初始化(self,n):
---->4 super().\uuuu init\uuun(n)
5.
6 def至_距离(自身,n):
TypeError:object.\uuuu init\uuuu()不接受任何参数
您可以尝试以下方法:
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
尽管我有点困惑,但即使这样似乎也行得通——也许对Python内部结构有更深入了解的人可以插话
等级速度(浮动):
定义初始化(self,n):
super()。\uuuu init\uuuuu()
def至_距离(自身,n):
返回自我*n
s=速度(2)
印刷版#2.0
打印(isinstance(s,float))#真实
印刷品(s**2)#4.0
z=s-2
打印(isinstance(z,速度))#错误
打印(isinstance(z,float))#真
打印(s.to_距离(3))#6.0
编辑-在调用s=Speed(2)
时,将print(self,n)
添加到\uuuuuu init\uuuuuu
将给出2.0 2
。我认为正在发生的是,\uuuu new\uuu
已经将self
设置为适当的值,因此n
不再需要在\uuu init\uu
中使用。删除super()。\uuuu init\uuuuu()
会产生与上面相同的结果,因此我们可以使用以下内容:
等级速度(浮动):
def至_距离(自身,n):
返回自我*n
EDIT2-您可能需要查看。此错误是因为您调用了
super.\uuuu init\uuu
而不是super()。但是,两种方法都不能传递值。也许只需将self.n=n
保存在\uuuu init\uuuuu
中?@Nathan很好地接受了我纠正的疏忽,尽管挑战仍然存在