[英]Python - Static Variable inside Function
I am trying to set a static variable inside a function. 我正在尝试在函数内设置静态变量。 Essentially, I want this variable to be
false
initially. 本质上,我希望此变量最初为
false
。 After the first time this function is called, I want the variable to be set to true
. 第一次调用此函数后,我希望将变量设置为
true
。
I currently have the following: 我目前有以下内容:
class LKTracker(object):
def track_points(self,width,height):
if not hasattr(track_points, "gotInitialFeatures"):
track_points.gotInitialFeatures = None
if not track_points.gotInitialFeatures:
#do some stuff
track_points.gotInitialFeatures = True
With this code, I keep receiving the following error: 有了这段代码,我不断收到以下错误:
NameError: global name 'track_points' is not defined
Anyone know what is happening here? 有人知道这里发生了什么吗?
In a global function, you can refer directly to the function object by looking up the name. 在全局函数中,可以通过查找名称直接引用函数对象。
This does not work in a method; 这并不在方法工作; you'd have to look the method up on the class instead:
您必须在类上查找该方法:
LKTracker.track_points
This still won't do what you want, however, because you'd get a unbound method object at that moment: 但是,这仍然无法完成您想要的操作,因为此时您将获得一个未绑定的方法对象:
>>> LKTracker.track_points
<unbound method LKTracker.track_points>
Method objects are created on demand (because functions are descriptors ), and creating an attribute on a method object is futile; 方法对象是按需创建的(因为函数是描述符 ),而在方法对象上创建属性是徒劳的。 they generally only live for a short while.
他们通常只活一小会儿。
You'd need to access the function instead: 您需要访问该函数:
>>> LKTracker.track_points.__func__
<function track_points at 0x103e7c500>
but you can do the same thing on self
: 但是您可以对
self
做同样的事情:
self.track_points.__func__
Now you can add a attribute: 现在,您可以添加一个属性:
track_points = self.track_points.__func__
if not hasattr(track_points, "gotInitialFeatures"):
track_points.gotInitialFeatures = None
if not track_points.gotInitialFeatures:
#do some stuff
track_points.gotInitialFeatures = True
But it would be much easier to just store that attribute on the class instead: 但是,仅将属性存储在类中会容易得多 :
if not hasattr(LKTracker, 'gotInitialFeatures'):
You shall init static variable before call a function. 您应在调用函数之前初始化静态变量。
def static_var(varname, value):
def decorate(func):
setattr(func, varname, value)
return func
return decorate
and now you can: 现在您可以:
@static_var("gotInitialFeatures", False)
def track_points(self, width, height):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.