2011-09-10 49 views
5

所以我有一個Table對象如下代碼,它有一個fieldnames屬性。描述符'getter'需要一個'property'對象,但收到一個'function'

class Table(object): 
    '''A CSV backed SQL table.''' 
    @property 
    def fieldnames(self): 
     with open(self.filename) as f: 
      return csv.DictReader(f).fieldnames 

    @property.setter 
    def fieldnames(self, fieldnames): 
     with open(self.filename, 'w') as f: 
      dr = csv.reader(f) 
      dw = csv.DictWriter(f, fieldnames=fieldnames) 
      dw.writerow(dict((field, field) for field in fieldnames)) 
      for row in self: 
       dw.writerow(row) 

當我嘗試導入該文件,我得到的錯誤:

seas486:PennAppSuite ceasarbautista$ python 
Python 2.7.1 (r271:86832, Jun 25 2011, 05:09:01) 
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin 
Type "help", "copyright", "credits" or "license" for more information. 
>>> import table 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "table.py", line 7, in <module> 
    class Table(object): 
    File "table.py", line 9, in Table 
    @property.getter 
TypeError: descriptor 'getter' requires a 'property' object but received a 'function' 

任何人能解釋一下這個錯誤意味着什麼?

回答

16

我想這相當於TypeError: unbound method ... must be called with ... instance as first argument (got ... instance instead)。要通過裝飾器將屬性添加到屬性,必須使用.setter作爲屬性對象的成員/方法,而不是作爲property的靜態方法/類方法。該代碼應該看起來像這樣:

class Table(object): 
    '''A CSV backed SQL table.''' 
    @property 
    def fieldnames(self): 
     with open(self.filename) as f: 
      return csv.DictReader(f).fieldnames 

    @fieldnames.setter # <<< 
    def fieldnames(self, fieldnames): 
     with open(self.filename, 'w') as f: 
      dr = csv.reader(f) 
      dw = csv.DictWriter(f, fieldnames=fieldnames) 
      dw.writerow(dict((field, field) for field in fieldnames)) 
      for row in self: 
       dw.writerow(row) 

另請參閱documentation中的示例。

相關問題