Правильно обновите переменную в Python

#python #variables

#python #переменные

Вопрос:

Я вызываю приведенную ниже функцию из другого модуля и пытаюсь обновить переменную cur по мере прохождения кода. Это довольно просто. Если атрибут move равен north, то переменная должна измениться с 1 на 2 . Однако это обновление не происходит, и я застрял. Я чувствую, что это должно быть очень просто. Как мне обновить эту переменную?

 import objects
def movement(move):
    cur = 1
    if cur == 1:
        if move == "north":
            cur = cur   1
            return "You stand in front of the white house."

        if move == "south":
            return "To the south there is tall grass as far as the eye can see.  But it is getting dark.  You decide to stay put."

        if move == "east":
            return "Darkness creeps up across the tall grassy feilds in the east.  You decide to stay put."

        if move == "west":
            return "You stand in a dark forest to the west."

    if cur == 2:
        if move == "south":         
            cur = cur - 1
            return "You stand facing a white house in the north.  Grassy feilds surround you and the sun is setting behind a forest in the west. "   objects.Mailbox.obj()
 

Комментарии:

1. откуда вы знаете, что переменная «cur» не была обновлена? это локальная переменная, если вы вызываете функцию из другого места, она не должна быть видна, поскольку она уничтожается в конце выполнения вашей функции

2. Каждый раз, когда вы вызываете функцию, cur снова устанавливается значение 1.

3. При обновлении не происходит ожидаете ли вы, что код введет второе условие if (т.Е. if cur == 2: )? Если нет, пожалуйста, уточните и уточните, что вас не устраивает.

Ответ №1:

если вы хотите, чтобы ваш cur был обновлен, вам нужно будет сделать movement классом и создать элемент следующим образом:

 import objects

class MovementClass:
    def __init__(self):
        self.cur = 1
    def movement(self, move):
        if self.cur == "north":
            self.cur  = 1
            return "You stand in front of the white house."

        if move == "south":
            return "To the south there is tall grass as far as the eye can see.  But it is getting dark.  You decide to stay put."

        if move == "east":
            return "Darkness creeps up across the tall grassy feilds in the east.  You decide to stay put."

        if move == "west":
            return "You stand in a dark forest to the west."

        if self.cur == 2:
            if move == "south":         
                self.cur -= 1
                return "You stand facing a white house in the north.  Grassy feilds surround you and the sun is setting behind a forest in the west. "   objects.Mailbox.obj()
 

Таким образом, ваша cur переменная будет обновлена, и вы сможете получить к ней доступ