如何在python中访问函数的内部变量并更改其值?

2024-04-19 05:02:04 发布

您现在位置:Python中文网/ 问答频道 /正文

>>> def nil():
...     ss='nil'
...     print ss
... 
>>> nil()
nil
>>> nil.ss='kk'
>>> nil()
nil
>>> print nil.ss
kk

我知道在python中所有的东西都是一个对象,所以function也是一个对象,现在我想更改存储在function中的'ss'变量的值,现在我尝试使用无ss但是它没有改变..两个“ss”之间的区别是什么?你知道吗


Tags: 对象deffunctionssprintnil区别kk
3条回答

函数是一个对象,但ss不是类中的成员变量。它是在函数体中定义的局部变量,不能在外部访问。改变它的唯一明智的方法就是改变功能的实现。你知道吗

def nil():
 ss='nil'

这是因为nil.ss没有指向nil函数中定义的变量ss。你知道吗

nil.ss表示ss现在是nil对象的属性。你知道吗

nil.ssss内部的nil()是完全不同的。你知道吗

>>> def nil():
    ss='foo'
    return ss

>>> nil.ss='bar'
>>> foo=nil()
>>> bar=nil()
>>> nil.ss
'bar'
>>> foo
'foo'
>>> bar
'foo'

第一个ss是函数的内部变量;第二个是函数的属性。它们不引用同一个对象。你知道吗

不过,这里有一个方法:

>>> def apple():
    if not hasattr(apple, 'ss'):  # This way it'll only be set inside the function once
        apple.ss = 'nil'
    return apple.ss

>>> apple()
'nil'
>>> apple.ss
'nil'
>>> apple.ss = 'kk'
>>> apple.ss
'kk'
>>> apple()
'kk'

相关问题 更多 >