许多语言支持ad-hoc polymorphism(也称为函数重载)开箱即用。但是,Python似乎没有选择它。不过,我可以想象,可能有一个技巧或者一个能够在Python中实现的技巧。有谁知道这样的工具?有没有办法在Python中获得ad-hoc多态性?
例如,在Haskell一个可能用它来生成测试数据,不同的类型:
-- In some testing library:
class Randomizable a where
genRandom :: a
-- Overload for different types
instance Randomizable String where genRandom = ...
instance Randomizable Int where genRandom = ...
instance Randomizable Bool where genRandom = ...
-- In some client project, we might have a custom type:
instance Randomizable VeryCustomType where genRandom = ...
这样做的好处是,我可以延长genRandom
为自己的自定义类型不接触测试库。
你会如何在Python中实现这样的东西?
提供一个你想到的或者它会如何帮助你的例子。 – Spaceghost
我添加了一个例子。希望这会赢得你的回票。 –
Python对方法没有强类型参数。只需要一个方法来检查输入的类型并作出相应的反应。同样的效果,不是吗? – RobertB