Python、"If if line is called on first time, do something else"

Python, "If if line is called on first time, do something else"

所以标题很容易解释,但我会更详细地介绍。我正在创建一个依赖文本的游戏,我将拥有数百万个区域。每次你进入一个新的区域,迎接你的只是一次与你之后再次进入同一个地方不同的反应,我需要找到一种方法来解决这个问题:

if len(line) == 1:
    do exclusive thing
else:
    do normal thing

当然,我可以使用像 "a = 0" 这样的计数器系统,但是我需要为我创建的每个区域创建一个单独的计数器,我不希望那样。

您需要静态变量:What is the Python equivalent of static variables inside a function?

def static_var(varname, value):
    def decorate(func):
        setattr(func, varname, value)
        return func
    return decorate

@static_var("counter", 0)
def is_first_time():
    is_first_time.counter += 1
    return is_first_time.counter == 1

print(is_first_time())
print(is_first_time())
print(is_first_time())

您可以只存储一个 dict 来跟踪房间访问情况,使用 defaultdict

可能更好
from collections import defaultdict

#Using a defaultdict means any key will default to 0
room_visits = defaultdict(int)

#Lets pretend you had previously visited the hallway, kitchen, and bedroom once each
room_visits['hallway'] += 1
room_visits['kitchen'] += 1
room_visits['bedroom'] += 1

#Now you find yourself in the kitchen again
current_room = 'kitchen'
#current_room = 'basement' #<-- uncomment this to try going to the basement next

#This could be the new logic:
if room_visits[current_room] == 0: #first time visiting the current room
    print('It is my first time in the',current_room)
else:
    print('I have been in the',current_room,room_visits[current_room],'time(s) before')

room_visits[current_room] += 1 #<-- then increment visits to this room