Python,“如果第一次调用行,则执行其他操作”

时间:2017-02-10 01:56:11

标签: python python-3.x numbers counter adventure

因此标题非常自我解释,但我会详细介绍。我正在创建一个依赖文本的游戏,我将拥有数百万个领域。每次你进入一个新的区域,你会受到一次只有不同的反应,而不是你以后再来到同一个地方,我需要找到一种方法:

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

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

2 个答案:

答案 0 :(得分:1)

您可以存储一个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

答案 1 :(得分:0)

您需要静态var: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())