问题描述
是否有可能在Python中创建一个维护变量
值的函数?
这样的东西:
globe = 0;
def myFun():
globe = globe + 1
返回地球
显然不可能那样做。我认为它可能是通过在变量前加上一些包上下文来完成的。
Python文档非常笨拙。在python doc中哪里是一个程序员
应该读一下Python中的包/模块系统如何工作?
(除了触及它的教程)
Xah
is it possible in Python to create a function that maintains a variable
value?
something like this:
globe=0;
def myFun():
globe=globe+1
return globe
apparently it can''t be done like that. I thought it can probably be
done by prefixing the variable with some package context...
the Python doc is quite stilted. Where in the python doc is a programer
supposed read about how the package/module system in Python works?
(besides the tutorial that touches it)
Xah
xa*@xahlee.org
http://xahlee.org/PageTwo_dir/more.html
推荐答案
简短的回答是使用全局声明:
globe = 0
def myFun():
全球地球仪
globe = globe + 1
返回地球仪
:
globe = 0
globe = myfun(全球)
def myFun( var):
返回var + 1
更优雅的是使用类和类属性而不是
全局变量。
-pu
The short answer is to use the global statement:
globe=0
def myFun():
global globe
globe=globe+1
return globe
more elegant is:
globe=0
globe=myfun(globe)
def myFun(var):
return var+1
and still more elegant is using classes and class attributes instead of
global variables.
-pu
除非您必须告诉它明确地表示你是使用全局的b $ b,否则Python会看到globe =并决定
你想要''globe''是一个局部变量。
globe = 0
def myFun():
全球全球
globe = globe + 1
返回地球
或者,换行值在一个可变的类型,所以你不必做任务
一个任务(并可以在嵌套范围内使用它):
globe = [0]
def myFun():
globe [0] + = 1
返回地球[0]
你可以用来隐藏函数外部代码的静态的hack滥用这个默认参数在定义时计算的事实:
def myFun(globe = [0]):
globe [0] + = 1
返回globe [0]
对于更复杂的情况,最好明确并使用
对象:
类计数器:
def __init__ (个体经营):
self.globe = 0
def count(个体经营):
self.globe + = 1
返回self.globe
myFun = Counter()。count
-
Andrew Clover
mailto:an*@doxdesk.com
This would work except that you have to tell it explicitly that you''re
working with a global, otherwise Python sees the "globe=" and decides
you want ''globe'' be a local variable.
globe= 0
def myFun():
global globe
globe= globe+1
return globe
Alternatively, wrap the value in a mutable type so you don''t have to do
an assignment (and can use it in nested scopes):
globe= [ 0 ]
def myFun():
globe[0]+= 1
return globe[0]
A hack you can use to hide statics from code outside the function is to
abuse the fact that default parameters are calcuated at define-time:
def myFun(globe= [ 0 ]):
globe[0]+= 1
return globe[0]
For more complicated cases, it might be better to be explicit and use
objects:
class Counter:
def __init__(self):
self.globe= 0
def count(self):
self.globe+= 1
return self.globe
myFun= Counter().count
--
Andrew Clover
mailto:an*@doxdesk.com
http://www.doxdesk.com/
这让我很难过。什么是myfun()?什么是var意图?
肯特
This mystifies me. What is myfun()? What is var intended to be?
Kent
这篇关于具有状态的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!