简体   繁体   English

python内部函数定义中的变量是什么?

[英]What's a variable in a inner function definition in python?

There is class definition in django of view in view.generic.base view.generic.base中的视图django中有类定义

class View(object):
    ...
    def as_view(cls, **initkwargs):
        """ 
        Main entry point for a request-response process.
        """
        ...

        def view(request, *args, **kwargs):
            self = cls(**initkwargs)
            if hasattr(self, 'get') and not hasattr(self, 'head'):
                self.head = self.get
            self.request = request
            self.args = args
            self.kwargs = kwargs
            return self.dispatch(request, *args, **kwargs)

        # take name and docstring from class
        update_wrapper(view, cls, updated=())

        # and possible attributes set by decorators
        # like csrf_exempt from dispatch
        update_wrapper(view, cls.dispatch, assigned=())
        return view

It should return a function like view(request, *args, **kwargs). 它应该返回像view(request,* args,** kwargs)这样的函数。 Notice there is a variable in 'def view', which is 'cls'. 注意“ def view”中有一个变量,即“ cls”。

Suppose we run: 假设我们运行:

tmp = View.as_view(), how will tmp(request, *args, **kwargs) know what is the value of cls? tmp = View.as_view(),tmp(request,* args,** kwargs)将如何知道cls的值是什么?


THIS IS THE SIMPLIFIED SITUATION!!!!! 这是简化的情况!

Say python code like this: 像这样说python代码:

>>> def func1(a):
...     def func2(b):
...         c = a + b
...         print c
...     return func2
... 
>>> func3 = func1(3)
>>> func3(1)
4
>>> func4 = func1(4)
>>> func3(1)
4
>>> func4(1)
5
>>> func3.a=5
>>> func3(1)
4
>>> func1.a=5
>>> func3(1)
4

What is 'a' in def of func3 actually and how did func3 get it? 实际上,func3中的“ a”是什么,func3如何获得它?


Update1: 更新1:

Thanks for answering. 谢谢回答。 The question was not totally expressed. 这个问题没有完全表达出来。

I think, when we call func3 = func1(3), we have two objects in the program, code of func1, object(symbol table) of called func1(3). 我认为,当我们调用func3 = func1(3)时,程序中有两个对象,即func1的代码,即被称为func1(3)的object(符号表)。

My questions are: 我的问题是:

  1. Is there an func2() object produced by calling code func1(), or the value of func3 is just a pointer to a member of the produced func1(3) which is the instruction of func2()? 是否存在通过调用代码func1()产生的func2()对象,或者func3的值只是指向所产生的func1(3)的成员的指针,而func2()的指令是该成员吗?

  2. Is the a of calling func3(1) in func1(3), or the object of func2()? 是在func1(3)中调用func3(1)的对象,还是func2()的对象?

You have created a closure by returning a function from another function. 您已经通过从另一个函数返回一个函数来创建了一个闭包

Using your simplified example, any variables that were in scope, and were referenced from your inner function func2 will remain in scope for as long as func2 continues to exist. 使用简化的示例,只要func2继续存在,作用域中并从内部函数func2引用的任何变量都将保留在作用域中。

So any variables declared inside func1 (including function parameters such as a ) are always accessible to func2 even after func1 ends. 所以内声明的任何变量func1 (包括函数参数,比如a )始终能够为func2后甚至func1结束。

The value that a has when func2 runs will be whatever value you passed to func1 to produce that particular instance of func2 func2运行时, a的值将是您传递给func1以生成该func2特定实例的任何值。

Let me explain what your code does 让我解释一下您的代码的作用

>>> def func1(a):
...     def func2(b):
...         c = a + b
...         print c
...     return func2
... 

This will create one function func1 which return you another function func2 . 这将创建一个函数func1 ,该函数将返回您另一个函数func2 func2 is local for func1 func2对于func1是本地的

>>> func3 = func1(3)

This will create variable func3 and value of func3 is func2 . 这将创建变量func3和价值func3func2 So when you print value of func3 it will return function. 因此,当您打印func3值时,它将返回功能。

>>> func3
<function func2 at 0x7fd29fcb66e0>

If you try to access func3.a then it will not return you 1 because a is not a attribute of func2 . 如果您尝试访问func3.a那么它将不会返回1因为a不是func2的属性。

>>> func3.a
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'a'

a is local variable, so you cant access it. a是局部变量,因此您无法访问它。 When you call func3 , it will call func2 with a as 1 . 当你调用func3 ,它会调用func2a1

>>> func3(1)
4

So this will call func2(1) where a is 3 in local func2 . 因此,这将调用func2(1) ,其中本地func2a3

I've run the same python program with some changes : 我运行了相同的python程序,但做了一些更改:

>>> def func1(a):
...     def func2(b):
...             c = a + b
...             print c
...             print a
...             print b
...     return func2
... 
>>> func3 = func1(3)
>>> func3(1)
4
3
1
  1. First of all when you call fun1(3), then the fun1 returns fun2, something like this 首先,当您调用fun1(3)时,fun1返回fun2,如下所示

def fun2(b):
    c = 3 + b
    print c
    print 3
    print b


2. Now, when you call function func3(1), you are effectively calling func2(1) 2.现在,当您调用函数func3(1)时,实际上是在调用func2(1)

It's the way it should work :) 它应该是这样的:)

For start, there is nothing recursive going on here, I guess you mean inner function definition. 首先,这里没有递归操作,我想您的意思是内部函数定义。 Inner function has access to surrounding scope (which is also called a closure). 内部函数可以访问周围的范围(也称为闭包)。 When you get your copy of function func3 it will have access to variables defined in outer function including parameter it's been called with 当您获得函数func3的副本时,它将可以访问外部函数中定义的变量,包括使用调用的参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM