Purpose of calling function without brackets python

后端 未结 6 555
独厮守ぢ
独厮守ぢ 2020-11-27 16:07

Consider the following:

class objectTest():

    def __init__(self, a):
        self.value = a

    def get_value(self):
        return self.value

class exec         


        
6条回答
  •  我在风中等你
    2020-11-27 16:38

    As mentioned, functions and methods are first-class objects. You call them by throwing some parentheses (brackets) on the end. But it looks like you want some more motivation for why python even lets us do that. Why should we care if functions are first-class or not?

    Sometimes you don't want to call them, you want to pass a reference to the callable itself.

    from multiprocessing import Process
    t = Process(target=my_long_running_function)
    

    If you put brackets after the above, it runs your my_long_running_function in your main thread; hardly what you wanted! You wanted to give Process a reference to your callable that it will run itself in a new process.

    Sometimes you just want to specify the callable and let something else...

    def do_something(s):
        return s[::-1].upper()
    
    map(do_something,['hey','what up','yo'])
    Out[3]: ['YEH', 'PU TAHW', 'OY']
    

    (map in this case) fill in its arguments.

    Maybe you just want to drop a bunch of callables into some collection, and fetch the one you want in a dynamic manner.

    from operator import *
    
    str_ops = {'<':lt,'>':gt,'==':eq} # etc
    op = str_ops.get(my_operator)
    if op:
        result = op(lhs,rhs)
    

    The above is one way to map string representations of operators onto their actual action.

提交回复
热议问题