正在使用 "function.variable = something" 全局变量

Is using "function.variable = something" a global variable

例如,如果我有这样的函数:

def function():
    function.number = 1

def calling():
    print(function.number)

function.number算全局变量吗?像这样调用变量是不可取的吗?

谢谢

不,它会被视为函数的一个属性。您可以查看 ipython:

In [1]: def function():
   ...:     function.number = 1
   ...:
   ...: def calling():
   ...:     print(function.number)
   ...:

In [3]: function()

In [4]: calling()
1

In [5]: dir()
Out[5]:
['In',
 'Out',
 '_',
 '__',
 '___',
 '__builtin__',
 '__builtins__',
 '__doc__',
 '__loader__',
 '__name__',
 '__package__',
 '__spec__',
 '_dh',
 '_i',
 '_i1',
 '_i2',
 '_i3',
 '_i4',
 '_i5',
 '_ih',
 '_ii',
 '_iii',
 '_oh',
 'calling',
 'exit',
 'function',
 'get_ipython',
 'quit']

In [6]: type(function)
Out[6]: function

In [7]: type(function.number)
Out[7]: int

In [8]: dir(function)
Out[8]:
['__annotations__',
 '__call__',
 '__class__',
 '__closure__',
 '__code__',
 '__defaults__',
 '__delattr__',
 '__dict__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__get__',
 '__getattribute__',
 '__globals__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__kwdefaults__',
 '__le__',
 '__lt__',
 '__module__',
 '__name__',
 '__ne__',
 '__new__',
 '__qualname__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'number']

function.number 是一个 表达式 ,其计算结果为某个对象的 number 属性的值。 function 本身是一个全局(或至少是非本地)变量,它被假定为引用具有 number 属性的对象。


严格来说,function是一个自由变量;名称解析的范围取决于定义 function 的上下文。例如,考虑

def foo():
    def function():
        function.number = 1
    
    def calling():
        print(function.number)

    function()
    calling()

这里,function是一个local变量,定义在foo的范围内,但它在[=的定义内部非本地使用13=] 和 calling.

没有。 如果你想拥有一个全局变量,你可以在全局范围内声明它。意思是:

number = 1

def function():
    something

def calling():
    some other thing

现在,如果函数中没有名为 number 的变量,您可以访问(读取)变量中的值。

如果您想从函数中修改变量,您需要使用关键字 global,如下所示:

number = 1

def function():
    global number
    number = 3

def calling():
    print(number)