2013-09-25 82 views
1

之前引用局部變量 '設置' 我試圖用set()奇怪的設置()錯誤。分配

adjacent = filter(lambda p: p[0] in xp and p[1] in yp, p_data) 
adjacent = set(adjacent) 

不過,我得到這個錯誤:

Traceback (most recent call last): 
    File "/home/anarchist/Desktop/python27/lib/python2.7/site-packages/gevent/greenlet.py", line 327, in run 

result = self._run(*self.args, **self.kwargs) 

File "/home/anarchist/Desktop/BSpaces/BrochureSpaces/imageProcessing/__init__.py", line 60, in findViewPorts 
    adjacent = set(adjacent) 

UnboundLocalError: local variable 'set' referenced before assignment 
<Greenlet at 0x15879b0: <bound method rawImage.findViewPorts of <BrochureSpaces.imageProcessing.rawImage instance at 0x7f7177356830>>(image_file='image_t.png')> failed with UnboundLocalError 

代碼:

class rawImage: 
def __init__(self, **kwargs): 
    logging.root.setLevel(logging.DEBUG) 

    self.p_data = [] # Positions of all non opaque pixels 

    gevent.spawn(self.findTransparent, **kwargs).join() 
    gevent.spawn(self.findViewPorts, **kwargs).join() 

def findTransparent(self, **kwargs):... 

def findViewPorts(self, **kwargs): 
    # Takes data and divides it into chunks that are continuous 
    self.view_ports = [] # Each entry is list of (x, y) 

    # Take first pixel, find all adjacent, transfer and delete 
    p_data = self.p_data 
    while p_data: 
     xp = range(p_data[0][0] - 1, p_data[0][0] + 2)  # + 2 because of the quirks of range 
     yp = range(p_data[0][1] - 1, p_data[0][1] + 2)  # Possible x, y ranges of adjacent pixels 

     _temp = [] 
     _temp.append((p_data[0][0], p_data[0][1])) 
     del p_data[0] 
     print xp, yp 

     adjacent = filter(lambda p: p[0] in xp and p[1] in yp, p_data) 
     adjacent = set(adjacent) 

     print adjacent, len(p_data) 
     while adjacent: 
      pixel = adjacent[0] 
      print pixel, '-' 
      xp = range(pixel[0] - 1, pixel[0] + 2) 
      yp = range(pixel[1] - 1, pixel[1] + 2)  # Possible x, y ranges of adjacent pixels 
      _temp.append((pixel[0], pixel[1])) 

      try: 
       print adjacent[0] 
       p_data.remove(adjacent[0]) 
       print p_data 
       del adjacent[0] 
      except BaseException as e: 
       logging.warning('findViewPorts %s', e) 
       return 
      adjacent.add(set(filter(lambda p: p[0] in xp and p[1] in yp, p_data))) 

     logging.debug('findViewPorts ' + str(_temp)) 
     self.view_ports.append(_temp) 
     break 

    for set in self.view_ports: 
     for x, y in set: 
      print x, y 
+0

我不能相信,我沒看出來 – Andrey

回答

6

不要使用內置函數作爲變量名稱,這會導致該錯誤:

for set in self.view_ports: 
     for x, y in set: 

文檔:Why am I getting an UnboundLocalError when the variable has a value?

+2

由於分配給'set'的功能('for'循環是一個隱含分配),'設置'是一個局部變量,它隱藏了內置類型'set'。當你嘗試使用'set()'創建一個集合時,它還沒有被分配,這就是爲什麼你在分配之前得到有關引用它的錯誤的原因。 – kindall