Skip to content

Instantly share code, notes, and snippets.

@winston-wen
Last active August 15, 2021 09:05
Show Gist options
  • Select an option

  • Save winston-wen/cfca19808c11f153d1f87e87acdd7156 to your computer and use it in GitHub Desktop.

Select an option

Save winston-wen/cfca19808c11f153d1f87e87acdd7156 to your computer and use it in GitHub Desktop.
python模拟C语言的静态局部变量
def fibonacci():
# 如果函数名太长, 为了编码的优雅方便, 建议起个别名.
ctx = fibonacci
# 在if not hasattr代码块里声明并初始化静态局部变量.
# 如果需要用到多个静态局部变量, 只需要检查一个用不到的变量(如ctx.init)是否存在.
# 完成初始化所需的静态局部变量之后, 记得初始化ctx.init. 如此这块代码才不会执行第二次.
if not hasattr(ctx, "init"):
ctx.a0, ctx.a1 = 1, 1
# ctx.init的赋值是随意的. 我的习惯是赋一个有意义的值.
ctx.init = "<<<Initialized>>>"
tmp = ctx.a0 + ctx.a1
print(tmp)
ctx.a0 = ctx.a1
ctx.a1 = tmp
for i in range(10):
fibonacci()

如果需要一个有状态的函数,

  • 如果状态很复杂 => 建议实现成class.
  • 如果状态较简单 => 建议实现成静态局部变量.
  • 当然也可以把状态实现在函数外面, 通过python import来初始化状态.
    • 后果是: 升级困难, 代码凌乱, 污染import.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment