调用函数的目的没有括号python

时间:2021-09-23 21:41:26

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解释器允许这种语法而不是引发属性错误,这在我的情况下会节省我宝贵的时间。

5 个解决方案

#1


14  

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?

如上所述,函数和方法是一流的对象。你通过在末尾抛出一些括号(括号)来调用它们。但看起来你想要更多的动机为什么python甚至让我们这样做。如果功能是一流的,我们为什么要关心?

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

有时你不想调用它们,你想要传递对callable本身的引用。

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.

如果你把括号放在上面,它会在你主线程中运行你的my_long_running_function;几乎没有你想要的!您希望为Process提供一个对callable的引用,它将在新进程中运行。

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

有时你只想指定callable并让别的东西......

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.

也许你只想将一堆callables放入某个集合中,然后以动态的方式获取你想要的那个。

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.

以上是将运算符的字符串表示映射到其实际操作的一种方法。

#2


13  

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.

通常情况下,你不会将方法与其他方法或其他任何方法进行比较,因为它并不是非常有用。一个有用的地方是你想将一个函数传递给另一个函数。

#3


3  

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_value equal to the method-reference b.get_value ?

3)方法引用a.get_value是否等于方法引用b.get_value?

This is perfectly valid Python :)

这是完全有效的Python :)

#4


1  

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

#5


0  

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

test1.py

import threading
from thread_test import ThreadTest

thread = threading.Thread(target=ThreadTest)
thread.start()
print('not blocked')

test2.py

test2.py

import threading
from thread_test import ThreadTest

thread = threading.Thread(target=ThreadTest())
thread.start()
print('not blocked')

test_thread.py

test_thread.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。

#1


14  

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?

如上所述,函数和方法是一流的对象。你通过在末尾抛出一些括号(括号)来调用它们。但看起来你想要更多的动机为什么python甚至让我们这样做。如果功能是一流的,我们为什么要关心?

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

有时你不想调用它们,你想要传递对callable本身的引用。

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.

如果你把括号放在上面,它会在你主线程中运行你的my_long_running_function;几乎没有你想要的!您希望为Process提供一个对callable的引用,它将在新进程中运行。

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

有时你只想指定callable并让别的东西......

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.

也许你只想将一堆callables放入某个集合中,然后以动态的方式获取你想要的那个。

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.

以上是将运算符的字符串表示映射到其实际操作的一种方法。

#2


13  

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.

通常情况下,你不会将方法与其他方法或其他任何方法进行比较,因为它并不是非常有用。一个有用的地方是你想将一个函数传递给另一个函数。

#3


3  

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_value equal to the method-reference b.get_value ?

3)方法引用a.get_value是否等于方法引用b.get_value?

This is perfectly valid Python :)

这是完全有效的Python :)

#4


1  

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

#5


0  

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

test1.py

import threading
from thread_test import ThreadTest

thread = threading.Thread(target=ThreadTest)
thread.start()
print('not blocked')

test2.py

test2.py

import threading
from thread_test import ThreadTest

thread = threading.Thread(target=ThreadTest())
thread.start()
print('not blocked')

test_thread.py

test_thread.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。