调用不带括号的函数python的目的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/21785933/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Purpose of calling function without brackets python
提问by user3311142
Consider the following:
考虑以下:
class objectTest():
    def __init__(self,a):
        self.value = a
    def get_value(self):
        return self.value
class execute():
    def __init__(self):
        a = objectTest(1)
        b = objectTest(1)
        print(a == b)
        print(a.get_value() == b.get_value)
        print(a.get_value() == b.get_value())
        print(a.get_value == b.get_value)
if __name__ == '__main__':
    execute = execute();
This code return
此代码返回
>>>
False
False
True 
False
Given that get_value is a function, I would expect the execution to stop and return an error, but it doesn't. Can somebody explain why the python interpreter allow this kind of syntax instead of raising an attribute error, which in my case would have saved me precious time.
鉴于 get_value 是一个函数,我希望执行停止并返回错误,但事实并非如此。有人可以解释为什么 python 解释器允许这种语法而不是引发属性错误,这在我的情况下会节省我宝贵的时间。
采纳答案by roippi
As mentioned, functions and methods are first-class objects. You callthem 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?
如前所述,函数和方法是一流的对象。您可以通过在末尾抛出一些括号(方括号)来调用它们。但看起来你想要更多的动机来解释为什么 python 甚至让我们这样做。为什么我们要关心函数是否是一流的?
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_functionin your main thread; hardly what you wanted!  You wanted to give Processa reference to your callable that it will run itself in a new process.
如果你在上面加上括号,它会my_long_running_function在你的主线程中运行;几乎没有你想要的!您想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']
(mapin this case) fill in its arguments.
(map在这种情况下)填写其参数。
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.
以上是将运算符的字符串表示映射到其实际操作的一种方法。
回答by Mark Ransom
Functions and methods in Python are also objects themselves. Thus you can compare them just as you would any other object.
Python 中的函数和方法本身也是对象。因此,您可以像比较任何其他对象一样比较它们。
>>> type(a.get_value)
<type 'instancemethod'>
>>> type(a.get_value())
<type 'int'>
Normally of course you wouldn't compare methods to each other or anything else, because it's not terribly useful. One place it's useful is when you want to pass a function into another function.
通常,您当然不会相互比较方法或其他任何方法,因为它不是非常有用。一个有用的地方是当您想将一个函数传递给另一个函数时。
回答by Morten Jensen
print(a.get_value() == b.get_value)   # 1
print(a.get_value() == b.get_value()) # 2
print(a.get_value == b.get_value)     # 3
1) Is return value of calling a.get_value()equal to the method b.get_value?
1) 调用的返回值是否a.get_value()等于方法b.get_value?
2) Does a.get_value()return the same as b.get_value()?
2)a.get_value()返回与b.get_value()?
3) Is the method-reference a.get_valueequal to the method-reference b.get_value? 
3) 方法引用是否a.get_value等于方法引用b.get_value?
This is perfectly valid Python :)
这是完全有效的 Python :)
回答by voronin
def mul(a, b):
    return a * b
def add(a, b):
    return a + b
def do(op, a, b):
    return op(a, b)
do(add, 2, 3)  # return 5
回答by Oppy
Several commentators want an example of where this is useful. One application is in threading. We need to pass the target to the thread without using brackets. Otherwise the target is created in the main thread, which is what we are trying to avoid.
一些评论员想要一个例子来说明这是有用的。一个应用程序是线程。我们需要在不使用括号的情况下将目标传递给线程。否则目标是在主线程中创建的,这是我们试图避免的。
Example:
例子:
In test1.py I call ThreadTest without using brackets. test_thread starts in the thread and allows test1.py to continue running.
在 test1.py 中,我不使用括号调用 ThreadTest。test_thread 在线程中启动并允许 test1.py 继续运行。
In test2.py, I pass ThreadTest() as the target. In this case the thread does not allow test2.py to continue running.
在 test2.py 中,我将 ThreadTest() 作为目标传递。在这种情况下,线程不允许 test2.py 继续运行。
test1.py
测试1.py
import threading
from thread_test import ThreadTest
thread = threading.Thread(target=ThreadTest)
thread.start()
print('not blocked')
test2.py
测试2.py
import threading
from thread_test import ThreadTest
thread = threading.Thread(target=ThreadTest())
thread.start()
print('not blocked')
test_thread.py
测试线程.py
from time import sleep
class ThreadTest():
    def __init__(self):
        print('thread_test started')
        while True:
            sleep(1)
            print('test_thread')
output from test1.py:
test1.py 的输出:
thread_test started
not blocked
test_thread
test_thread
test_thread
output from test2.py:
test2.py 的输出:
thread_test started
test_thread
test_thread
test_thread
I am using python3.5 on Linux Mint.
我在 Linux Mint 上使用 python3.5。
回答by Akshay Vashishtha
Difference between function without parentheses and with parentheses is that when using parentheses you will get the output of that function and when you use the function without parentheses you create a copy of that function. for example
不带括号的函数和带括号的函数之间的区别在于,当使用括号时,您将获得该函数的输出,而当您使用不带括号的函数时,您将创建该函数的副本。例如
def outerFunction(text): 
    text = text 
    def innerFunction(): 
        print(text) 
    return innerFunction()
if __name__ == '__main__': 
    outerFunction('Hey!') 
    x = outerFunction
    y = x 
    x('Hey i am busy can you call me later')
    y('this is not a function')
here we copy the function outerFunction to x and then copy y to x.
这里我们将函数outerFunction 复制到x,然后将y 复制到x。

