Python script:
def show(name):
def getName():
return _name
def setName(value):
_name = value
_name = ''
print('Input parameter: ', name)
print('Global variable: ', say_hello)
print('Change private variable: ', setName(name))
print('Get private variable: ', getName())
print('Private variable: ', _name)
print('Input parameter: ', name)
say_hello = 'hello'
show('Jim')
Output:
Input parameter: Jim
Global variable: hello Change
private variable: None
Get private variable:
Private variable:
Input parameter: Jim
Why doesn’t the inner function change the value of _name, yet the function show can get the value of say_hello? I know it's a variable scope problem, but I want to know some detail.
-
My python version is Python 3.2 (r32:88445, Feb 21 2011, 11:29:37).dghost– dghost2011年09月22日 03:46:07 +00:00Commented Sep 22, 2011 at 3:46
-
Thanks for helping me to explain my question! Thanks all of you! :^)dghost– dghost2011年09月22日 03:47:56 +00:00Commented Sep 22, 2011 at 3:47
3 Answers 3
Assignments in functions are assigned in the functions local scope. setName assigns _name in the local scope in setName, the outer _name is unaffected.
In Python 2.X, it is possible to assign to the module global scope by using the global statement, but not to an outer local scope.
Python 3.X adds the nonlocal statement (see PEP-3104 for details if you are interested). In your example, nonlocal could be used in setName to assign to the outer local scope.
This blog post discusses variable scoping in Python with some nice examples and workarounds (see example 5 specifically).
1 Comment
_name is, in this case, local to the setName() function, as every variable name is when assigned to in a function.
Unless you have a global statement, or in 3.x, a nonlocal statement - which would help you in this case.
Comments
Why not moving show as a say_hello method?
class SayHello(unicode):
_name = u""
def get_name(self):
return self._name
def set_name(self, value):
self._name = value
def show(self, name):
self.name = name
print(self, self.name)
name = property(get_name, set_name)
say_hello = SayHello('hello')
say_hello.show('Jim')
You should avoid using global variables if not strictly necessary.