Python 定义一个生成器,该生成器在第一次_下一次_()调用之前更新全局变量

Python 定义一个生成器,该生成器在第一次_下一次_()调用之前更新全局变量,python,oop,generator,Python,Oop,Generator,给定python中的以下函数,我希望在调用“next()”之前更新全局变量。让我举个例子给你看 # some script happening before # a (global) variable is created L = 0 def generate(batch=128, ID=0, YIND=0): # just a call to a global dictionary x_, y_ = global_dict[id_to_keys[ID]] # update

给定python中的以下函数,我希望在调用“next()”之前更新全局变量。让我举个例子给你看

# some script happening before
 
# a (global) variable is created
L = 0

def generate(batch=128, ID=0, YIND=0):

  # just a call to a global dictionary
  x_, y_ = global_dict[id_to_keys[ID]]

  # update global variable please
  global L
  L = len(x_)

  X,Y=[],[]
  counter=0

  for i,x in enumerate(x_):

    counter+=1
    X.append(x)
    Y.append(y_[i])

    if counter==batch: 

      counter=0
      yield np.asarray(X[-batch:]), np.asarray(Y[-batch:])
然后您可以运行:

print(L)
g = generate()
print(f'I would like this to output some number but it outputs ',L)
_ = g.__next__()
print(f'I would like this to output some number and it outputs ',L)
其输出如下:

I would like this to output some number but it outputs 0
I would like this to output some number and it outputs 12312
最后:请注意,有一种方法可以通过具有类变量的类定义来实现这一点,但我目前想知道是否有完整的“功能性”实现


感谢您抽出时间

我不完全确定我是否正确理解了您的意图。但问题是Python中的生成器函数只有在枚举生成器时才开始执行:

def gen():
打印('1'之前)
收益率1
打印('2'之前)
收益率2
打印('2'之后)
>g=gen()
>>>下一个(g)
1之前
1.
>>>下一个(g)
2点之前
2.
>>>下一个(g)
2点以后
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
下一个(g)
停止迭代
因此,如果要在枚举生成器之前运行代码,则不能将该代码作为生成器函数本身的一部分

您可以改为使用一个普通函数来执行某些操作,然后返回一个已创建的生成器:

def gen_internal():
收益率1
打印('2'之前)
收益率2
打印('2'之后)
def gen():
打印('1'之前)
返回gen_内部()
>g=gen()
1之前
>>>下一个(g)
1.
>>>下一个(g)
2点之前
2.
>>>下一个(g)
2点以后

由于您显然只在第一次屈服之前设置了
L
,这可能是您想要做的。

是的,您理解正确。我会接受这个答案,因为它正是我所说的我想做的。