想法

在Python的哲学里,函数不强制要有返回值,
对于没有reutrn的函数解释器会自作主张返回一个None
因此,可以用函数实现过程封装。

问题

函数内部变量都是局部的,相当于namespace限定在这个函数里,无法影响全局,例如:

>>> def init():
...     x=0
... 
>>> init()
>>> x
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'x' is not defined

解决

使用global关键字声明变量为全局有效

>>> def super_init():
...     global x
...     x = 0
... 
>>> super_init()
>>> x
0

相关文章:

  • 2022-12-23
  • 2021-12-26
  • 2021-09-09
  • 2021-12-26
猜你喜欢
  • 2021-12-11
  • 2021-07-12
  • 2021-06-24
  • 2021-11-28
  • 2021-08-13
  • 2022-02-20
相关资源
相似解决方案