简体   繁体   中英

Change global string within a method in python 3

I googled my problem but haven't been able to find an answer. My problem is: I'm trying to change a string within a method in python 3. I'm trying a little code like this:

number_a = 0
number_b = 1

word = 'empty'

def something():
    if number_a > number_b
        word = 'hello'
    else: 
        word = 'goodbye'

something()
print(word)

What Python is giving me for output is

empty

What am I doing wrong here?

Functions assume variables are local and assigning a value will by default create a new local variable to contain it. The non-local, global variable remains unaffected.

This is desirable. Otherwise you'd have to create unique names for everything and always risk accidentally overwriting an important global variable.

You can change this behaviour by explicitly telling Python that it's the global variable that you want to assign a value to. For that, use the global keyword to explicitly link the local name to the global variable:

def something():
    global word

    if number_a > number_b
        word = 'hello'
    else: 
        word = 'goodbye'

Sometimes this is necessary. In your simple example, however, it would probably be better to just return the value and do the assignment outside of the function. That way the function isn't tied to the surrounding namespace:

def something(number_a, number_b):
    if number_a > number_b
        return 'hello'
    else: 
        return 'goodbye'

word = something(a, b)

The issue here is that you aren't modifying the string, you are reassigning a local variable. That variable does not have scope outside the function unless you declare that the name word has global binding. So to fix the problem you need to tell the interpreter that you're affecting the global variable inside your function.

def something():
  global word
  ...

The word variable is only shadowing the word variable outside of the function. It's a scope problem. If you want to actually change word you could use the global keyword, but a more pythonic approach would be something like this:

number_a = 0
number_b = 1

word = 'empty'

def something():
    if number_a > number_b:
        word = 'hello'
    else: 
        word = 'goodbye'
    return word

word = something()
print(word)

One other clarification is that what you have written is a function and not a method .

Methods are associated with objects.

A simpler way to write this function would be something more like this:

def something():
    return 'hello' if number_a > number_b else return 'goodbye'

Then you wouldn't have to shadow the word variable at all.

You would need to use the global keyword as word in your function is local to that function but that is generally not the way to go, you can return the result and reassign word to the returned value:

word = 'empty'

def something():
   return 'hello'if number_a > number_b else  'goodbye'

word = something()
print(word)

Another way would be to put the word in a mutable structure:

word = ['empty']


def something():
    if number_a > number_b:
        word[0] = 'hello'
    else:
        word[0] = 'goodbye'
something()
print(word[0]) -> "goodbye"

But really if you want values to change globally like that you should probably use a class where word is an attribute:

class Foo():
    def __init__(self,word,n1,n2):
        self.word = word
        self.number_a = n1
        self.number_b = n2

    def something(self):
        if self.number_a > self.number_b:
            self.word = 'hello'
        else:
            self.word = 'goodbye'

inst = Foo("empty",0,1)

inst.something()
print(inst.word)
goodbye

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