Is this an example of python function overload?

后端 未结 3 1678
伪装坚强ぢ
伪装坚强ぢ 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.

    0 讨论(0)
  • 2021-01-29 06:23

    Python, in some sense, doesn't need a function overloading capability when other languages do. Consider the following example in C:

    int add(int x, int y) {
        return x + y;
    }
    

    If you wish to extend the notion to include stuff that are not integers you would need to make another function:

    float add(float x, float y) {
        return x + y;
    }
    

    In Python, all you need is:

    def add(x, y):
        return x + y
    

    It works fine for both, and it isn't considered function overloading. You can also handle different cases of variable types using methods like isinstance. The major issue, as pointed out by this question, is the number of types. But in your case you pass the same number of types, and even so, there are ways around this without function overloading.

    0 讨论(0)
  • 2021-01-29 06:32

    overloading methods is tricky in python. However, there could be usage of passing the dict, list or primitive variables.

    I have tried something for my use cases, this could help here to understand people to overload the methods.

    Let's take the example:

    a class overload method with call the methods from different class.

    def add_bullet(sprite=None, start=None, headto=None, spead=None, acceleration=None):

    pass the arguments from remote class:

    add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},accelaration=10.6}

    OR add_bullet(sprite = 'test', start=Yes,headto={'lat':10.6666,'long':10.6666},speed=['10','20,'30']}

    So, handling is being achieved for list, Dictionary or primitive variables from method overloading.

    try it out for your codes

    0 讨论(0)
提交回复
热议问题