Python - 在变量中存储函数 [英] Python - Store function in variable

查看:121
本文介绍了Python - 在变量中存储函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将函数存储在变量中的概念,这使得我更容易。但我有问题,变量中的值不是每次都动态调用函数。所以它始终返回相同的值。为了解决这个问题,我做了一个代码片断来简单地说明它:



pre $ def $($) :
resp = requests.get('http://www.google.com').elapsed.total_seconds()
return resp

test = value()

而真:
印刷测试
time.sleep(10)

输出:

  0.00649 
0.00649

在这种情况下,当我打印测试时,在 while true 时,它返回相同的值,即使我我正在调用函数 value()。我该如何解决这个问题?我知道我可以把这个函数放在while循环中,但是我想把它作为一个变量。 解决方案

以前的答案是正确的,但请让我详细说明。



在Python的世界中,事物具有非常精确的含义,但如果您刚刚入门,并不总是清楚如何。 表达式是具有的元素, / code>, some_variable 10/2 。名称 some_variable 被称为标识符,仅仅是因为它标识了一个值。就像Scruffy的名字可能会识别你的狗一样。

语句是影响程序流程或程序状态的因素,但缺少值。以下是声明的示例:

  if x> 10:
x - = 1



  def foo(x):
print(x的值是,x)

与JavaScript不同,例如,几乎所有东西都是表达式(并且有值),您 不能 执行此操作:

  my_function = def foo(x):print(x的值是,x)

前面的 def 语句将创建一个函数名称 foo ,但该语句本身没有值。但是,名称 foo 会引用一个值。这意味着当你写 foo 时,这个值就是一个东西,而这个东西是一个函数!



另一方面,表达式 x()会做 两个 事情。首先它会查找标识符 x 的值。希望这个值是一个函数。之后,括号表示该值将被称为。如果 x 不是一个函数,那么会发生什么?

 > >> x = 10 
>>> x()
Traceback(最近一次调用的最后一个):
在< module>中,第1行的文件< ipython-input-3-7354d77c61ac>
x()
TypeError:'int'对象不可调用

错误:10不是可调用的。 Callable表示可以像函数一样调用的东西。



括号是,如您所知,是一系列参数。在这种情况下,列表只是空的,所以当你写 x()时,你会说调用'x'所指的任何名字,但不要发送任何参数 。

函数调用总是有一个值,因为它是一个表达式。如果你没有明确地返回任何东西,那么它的值就会是 None



要回答你的问题,最后,让我们玩替代游戏。规则很简单,任何表达式都可以用它的值代替:

  def value():
resp =请求.get('http://www.google.com').elapsed.total_seconds()
return resp

这是一个声明,所以它没有任何价值。然而,一个函数是用名字 value 创建的。



函数由两个语句组成),一个变量赋值和一个返回语句。



然而, = 右边的是一个表达式。小故事:

$ ul
$ li $ 请求指的是请求模块

  • get 指的是上述模块中的模块全局函数
  • get ('...')正在调用这个函数,并返回一些东西。

  • something有一个名为的属性,它有一个名为 total_seconds 的属性。

  • total_seconds 是一个指向可调用对象的标识符。调用可调用时不带任何参数( total_seconds()),并返回一些结果。可能是一个以名字为基础的数字。假设它的价值总是 10 ,为简单起见。



  • 是另一项任务:

      test = value()

    这可以认为是让名称'test'引用由名称'value'标识的可调用函数在用空参数调用时返回的值清单。在我们的例子中,名为 value 的函数对象将被调用, resp 将被赋值为 10 ,那么 return 语句会让调用者知道这个调用正在发送值 10 返回。从现在开始,名称 test 会引用 10 的值。



    让我们快速浏览循环:

      while True:
    print test
    time.sleep(10)

    执行以下操作直到时间结束:



    $ ul
  • print (Python 2中的语句,Python 3中的表达式)具有以下副作用:将东西印刷到屏幕上。在这种情况下,无论表达式 test 的值是多少,它都不会产生太大的影响。 我们已经知道标识符 test 指的是 10 的值。它只会在屏幕上打印10。
  • 休息十秒钟。

  • 重复。

  • ul>

    您可能想要在循环的每次迭代中调用某个函数(invoke基本上是拉丁语call,我喜欢花哨的词)。否则,程序会一遍又一遍地打印10,10,10。为了解决这个问题,你首先必须改变表达式作为 print 语句的一部分从标识符( test )函数调用:

      print test()

    但是,正如我们前面看到的那样,由于 10 不是一个可调用的函数,所以会引发一个大胖子错误。为了解决这个问题(这就是程序员所做的,对吗?)你还需要从 10 更改 test 的值,因为它不是可调用的函数。一个函数可以简单地用它的名字来引用,所以只需改变这一行:

      test = value()#equals ten 

    至此:

      test = value#等于名为value的函数

    函数现在有两个名称,旧名称值和新名称测试。循环中的每一步都会再次请求页面,并返回完成请求所需的时间 new 。如果请求超时,您将遇到不同类型的崩溃,但这是另一回事。



    更多信息可以在 Python Language Reference


    I have a concept where I store function in variables which makes it easier for me. But I am having the problem that the value in the variable isn't dynamically calling the function each time. So it returns the same value all the time. Just to make clear of the problem, I have made a code snip to illustrate it in a easy way:

    def value():
            resp = requests.get('http://www.google.com').elapsed.total_seconds()
            return resp
    
    test = value()
    
    while True:
            print test
            time.sleep(10)
    

    Output:

    0.00649
    0.00649
    

    In this case, in the while true when I print test, it returns the same value, even though I am calling the function value(). How can I solve this issue? I know I can put the function in the while loop, but I want to have it as a variable.

    解决方案

    The previous answers are correct, but please let me elaborate.

    In the world of Python, things have very precise meanings but it's not always clear what is what if you are just getting started.

    Expressions are things that have a value, and they include things like 123, some_variable and 10 / 2. The name some_variable is called an identifier, simply because it identifies a value. Just like the name Scruffy might identify your dog.

    Statements are things that affect the program flow or the state of your program, but lack a value. The following are examples of statements:

    if x > 10:
        x -= 1
    

    And

    def foo(x):
        print("The value of x is", x)
    

    Unlike in JavaScript, for example, where almost everything is an expression (and has a value), you can not do this:

    my_function = def foo(x): print("The value of x is", x)
    

    The previous def statement will create a function by the name foo, but the statement itself doesn't have a value. The name foo will refer to a value, however. It means that when you write foo, the value will be a thing, and this thing is a function!

    The expression x() on the other hand will do two things. First it will look up the value of the identifier x. Hopefully this value is a function. After that, the parentheses means that the value will be called. What happens if x is not a function, then?

    >>> x = 10
    >>> x()
    Traceback (most recent call last):
      File "<ipython-input-3-7354d77c61ac>", line 1, in <module>
        x()
    TypeError: 'int' object is not callable
    

    Big Fat Error: 10 is not a "callable". Callable means something that can be called like a function.

    The parentheses are, as you probably know, a list of arguments. In this case the list is simply empty so when you write x() you are saying "call whatever the name 'x' is referring to but don't send any arguments".

    A function call always has a value, since it's an expression. If you don't explicitly return anything, the value will simply be None.

    To answer your question, finally, let's play the substitution game. The rules are simple, any expression can be replaced by its value:

    def value():
        resp = requests.get('http://www.google.com').elapsed.total_seconds()
        return resp
    

    This is a statement, so it doesn't have a value. A function is created with the name value, however.

    The function consists of two statements (no value, again), a variable assignment and a return statement.

    The thing to the right of the = is an expression however. Short story:

    • requests is referring to the requests module
    • get is referring to a module-global function in the above module
    • get('...') is calling this function, and something is returned.
    • The "something" has a property called elapsed, which has a property called total_seconds.
    • total_seconds is an identifier that refers to a callable. The callable is called without any arguments (total_seconds()) and something is returned. Probably a number, based on the name. Let's say its value is always 10, for simplicity.

    The next statement is another assignment:

    test = value()
    

    This can be thought of as "let the name 'test' refer to the value that is returned by the callable identified by the name 'value' when it is called with an empty argument list". In our case, the function object called value will be called, resp will be assigned the value 10, then the return statement will let the caller know that this call is sending the value 10 back. The name test will refer to the value 10, from now on.

    Let's go over the loop, quickly:

    while True:
        print test
        time.sleep(10)
    

    Do the following until the end of Time:

    • print (a statement in Python 2, an expression in Python 3!) has the side-effect of printing stuff to the screen. Otherwise it doesn't do much.
    • The stuff, in this case, is whatever the value of the expression test is. We already know that the identifier test is referring to the value 10. It will simply print "10" to the screen.
    • Sleep for ten seconds.
    • Repeat.

    You probably want to invoke some function at each iteration of the loop ("invoke" is basically latin for "call", I like fancy words). Otherwise the program will just print "10", "10", "10", over and over again. To fix this this, you first have to change the expression evaluated as part of the print statement from just an identifier (test) to a function call:

    print test()
    

    But this will, as we saw before, raise a Big Fat Error since 10 is not a callable function. To fix it (that's what programmers do, right?) you also need to change the value of test from 10, since it's not a callable, to the function. A function can be referred to simply by its name, so just change this line:

    test = value()  # equals ten
    

    To this:

    test = value  # equals the function called "value"
    

    The function now has two names, the old name "value", and the new name "test". Each step in the loop will request the page again and return the new time it took for the request to complete. If the request times out you will have a different kind of crash, but that's another story.

    Further information can be found in the Python Language Reference.

    这篇关于Python - 在变量中存储函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆