好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

overloader:在Python中实现重载

overloader:在Python中实现重载

诗书塞外 Python程序员

Python中实现重载,一般都需要对参数进行识别和转化。这样做不是很直观,需要添加一些琐碎的逻辑。所以boramalper实现了overloader这个库,来帮助Python增加重载的特性。

使用了overloader的代码看起来像这样,和c++/java中的重载特性非常的相似。

 
import typing
from overloader import overload

@overload
def simple_func(a, b):
    return "First simple_func"

@overloa
ddef simple_func(a, b, c, d=32, *, ka, dka="default"):
        return "Second simple_func"

print(simple_func(3, 14))
print(simple_func(3, 14, 15, ka="pi"))

@overload
def typed_func(a: typing.Union[int, float], d: typing.Dict[int, int]):
    return "First typed_func"

@overload
def typed_func(a: int, b: typing.Dict[int, str]):
    return "Second typed_func"

print(typed_func(2, {71: 82}))
print(typed_func(2, {71: "a string"}))

"""
Works for normal methods and staticmethods as well.
"""
class C:    
 @classmethod
    @overload
    def class_method(cls, a: str, b: int):
         return "First class_method"

    @classmethod
    @overload
    def class_method(cls, a: str, b: float):
        return "Second class_method"
 
c = C()
print(c.class_method("pi", 3))
print(c.class_method("e", 2.7182)) 

如果你对这个库感兴趣,可以安装并尝试它:

 
pip3 install overloader 

该项目的地址在 https://github测试数据/boramalper/overloader

查看更多关于overloader:在Python中实现重载的详细内容...

  阅读:45次