can a python function call a global function with the same name?

后端 未结 2 794
礼貌的吻别
礼貌的吻别 2021-01-13 01:50

Can I call a global function from a function that has the same name?

For example:

def sorted(services):
    return {sorted}(services, key=lambda s: s         


        
2条回答
  •  耶瑟儿~
    2021-01-13 02:18

    Store the original function reference before define a new function with the same name.

    original_sorted = sorted
    
    def sorted(services):
        return original_sorted(services, key=lambda s: s.sortkey())
    

    For, builtin functions like sorted, you can access the function using __builtin__ module (In Python 3.x, builtins module):

    import __builtin__
    
    def sorted(services):
        return __builtin__.sorted(services, key=lambda s: s.sortkey())
    

    But, both which shadow builtin function is not recommended. Choose other name if possible.

提交回复
热议问题