如何在函数调用之间维护变量值

2024-03-29 06:05:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建一个函数来填充一个缓冲区,这个缓冲区被多次调用。我声明rep_counter以在每次传递后保持其值,但是当我再次调用它时,它将重置为0。我试着在def __init__内将它声明为self.rep_counter,试着将它声明为global函数,但没有任何运气。我该怎么做?这是我的实际代码:

import gym
import cv2
import numpy as np
from collections import deque

env = gym.make('SpaceInvaders-v0')
env.reset()
action_size = env.action_space.n
state_size = env.observation_space.shape
steps =  0 
step_counter = 0          
total_reward = 0
i = 0
i_update = i
episodes = 100010
img_batch_size = 4
img_batch = []
state1, reward1, _, _ = env.step(0)
batch_shape = (1,80,80,4)
img_batch = [state1,state1,state1,state1]
exp_batch = []
rep_batch = []
rep_batch_size = 4
rep_counter = 0
memory_length = 2
memory = deque((), maxlen = memory_length)
rep_batch = deque((), maxlen = rep_batch_size)


class AI:          
    def replay(self, exp_batch, rep_counter):
        if rep_counter < rep_batch_size:
            rep_counter += 1
            rep_batch.append(exp_batch)            
        else:
            if len(memory) < memory_length:
                memory.append(rep_batch)
            else:
                memory.popleft()
                memory.append(rep_batch)
            rep_batch.popleft()
            rep_batch.append(exp_batch)
            rep_counter = 0


    def buffer_processing(img_batch):
        processed_batch = [cv2.resize(cv2.cvtColor(x,cv2.COLOR_RGB2GRAY),(80,80)) for x in img_batch]
        processed_batch = [[x/255.0]for x in processed_batch]
        processed_batch = np.asarray(processed_batch)
        processed_batch.shape = batch_shape
        return processed_batch

    a = buffer_processing(img_batch)

for i in range (episodes):
    total_reward = 0

    for steps in range (10000):
        action = env.action_space.sample()
        next_state, reward, done, _ = env.step(action)
        total_reward += reward
        state = next_state
        exp_batch = (state, action, next_state, reward, done)
        agent = AI()
        agent.replay(exp_batch, rep_counter)
        exp_batch = []
        step_counter += 1



Tags: importenvimgsizebatchcounteractioncv2
1条回答
网友
1楼 · 发布于 2024-03-29 06:05:38

在等待一个最小的完整的工作示例时,这里的注释中指定了一些可能的建议。你知道吗

您可以将它声明为全局的,然后在函数中引用它作为global rep_counter,然后再使用它。你知道吗

您可以将它声明为任何方法内的实例变量(如果__init__更好)为self.rep_counter。你知道吗

可以将其声明为类变量(其值在所有实例中共享):

class AI:
    rep_counter

并称之为AI.rep_counter。你知道吗

如果我们讨论纯函数,可以使用一种方法来回忆C/C++静态关键字:

def myFunction():
    ...
    myFunction.NumberOfCalls += 1

myFunction.NumberOfCalls = 0

相关问题 更多 >