Is this an example of python function overload?

后端 未结 3 1695
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 06:07

I know python does not allow us to overload functions. However, does it have inbuilt overloaded methods?

Consider this:

setattr(object_name,\'variable\',         


        
3条回答
  •  暖寄归人
    2021-01-29 06:23

    The function setattr(foo, 'bar', baz) is always the same as foo.bar = baz, regardless of the type of foo. There is no overloading here.

    In Python 3, limited overloading is possible with functools.singledispatch, but setattr is not implemented with that.

    A far more interesting example, in my opinion, is type(). type() does two entirely different things depending on how you call it:

    1. If called with a single argument, it returns the type of that argument.
    2. If called with three arguments (of the correct types), it dynamically creates a new class.

    Nevertheless, type() is not overloaded. Why not? Because it is implemented as one function that counts how many arguments it got and then decides what to do. In pure Python, this is done with the variadic *args syntax, but type() is implemented in C, so it looks rather different. It's doing the same thing, though.

提交回复
热议问题