大数跨境

overloader:在Python中实现重载

overloader:在Python中实现重载 Python程序员
2016-02-28
0
导读:Python中实现重载,一般都需要对参数进行识别和转化。这样做不是很直观,需要添加一些琐碎的逻辑。所以bor


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.com/boramalper/overloader

【声明】内容源于网络
0
0
Python程序员
1234
内容 2525
粉丝 0
Python程序员 1234
总阅读0
粉丝0
内容2.5k