Python - Static Variable inside Function

孤街醉人 提交于 2019-12-22 00:05:21

问题


I am trying to set a static variable inside a function. Essentially, I want this variable to be false initially. After the first time this function is called, I want the variable to be set to 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?


回答1:


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.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'):



回答2:


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):
   ...


来源:https://stackoverflow.com/questions/19585801/python-static-variable-inside-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!