Decorator for overloading in Python

前端 未结 3 1513
礼貌的吻别
礼貌的吻别 2020-12-15 00:47

I know it\'s not Pythonic to write functions that care about the type of the arguments, but there are cases when it\'s simply impossible to ignore types because they are han

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-15 01:00

    This doesn't directly answer your question, but if you really want to have something that behaves like an overloaded function for different types and (quite rightly) don't want to use isinstance then I'd suggest something like:

    def func(int_val=None, str_val=None):
        if sum(x != None for x in (int_val, str_val)) != 1:
            #raise exception - exactly one value should be passed in
        if int_val is not None:
            print('This is an int')
        if str_val is not None:
            print('This is a string')
    

    In use the intent is obvious, and it doesn't even require the different options to have different types:

    func(int_val=3)
    func(str_val="squirrel")
    

提交回复
热议问题