简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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