开发者

Python variable scope issue

Python script:

def show(name):
    def getName():
        return _name
    def setName(value):
        _name = value
    _name = ''
    print('Input parameter: ', name)
    print('Global variable: ', say_hello)
   开发者_如何学Python 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.


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).


_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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜