Python中的寄存器/触发器实现

2024-05-15 15:26:31 发布

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

我需要对硬件设计进行Python模拟。设计中有寄存器(即一些数据在时钟之间存储)

在MATLAB中,我只声明持久变量,它将在函数调用之间存储数据(刷新非持久变量)

经过一些搜索和浏览之后,我找到了使用生成器和类的选项,但这两个选项似乎都有点麻烦

我的问题是:

有没有一种简单的方法来声明函数中的一些变量,让它们在调用该函数之间存储数据?类似于以下伪代码:

myfunc(some inputs)
    declare persistent aa,bb,cc 
    if running_first_time:
        aa,bb,cc = 0
        xx,yy = 0

    else:
        <do some logical and algebraic stuff with inputs and 
        aa,bb,cc store some results in aa,bb,cc until the 
        next function call, calculate xx and yy outputs>
    return xx,yy

Tags: and数据函数声明硬件选项some时钟
2条回答

肾盂途径是一个闭合。在Python中,您定义一个外部函数来初始化持久变量,定义一个内部函数并返回它。然后,内部函数可以使用持久变量:

def builder():
    tot = 0
    def foo(x):
        nonlocal tot
        tot += x
        return tot
    return foo

用法:

>>> foo = builder()
>>> foo(1)
1
>>> foo(2)
3
>>> foo(5)
8

以下是如何使用生成器实现此功能:

def myfunc(some, inputs):
    aa = bb = cc = xx = yy = 0
    while True:
        some, inputs = yield xx, yy
        # do some stuff with some, inputs, aa, bb, cc, xx, yy...

您将使用的方式如下:

>>> func_instance = myfunc(first, inputs)
>>> first_xx, first_yy = next(func_instance)
>>> second_xx, second_yy = func_instance.send((second, inputs))
>>> # etc.

生成器,尤其是那些使用.send的生成器,需要花一些时间来适应,但功能非常强大

相关问题 更多 >