2011-09-10 3 views
5

テーブルオブジェクトのこのコードは以下のとおりです。フィールド名のプロパティもあります。記述子 'getter'は 'プロパティ'オブジェクトを必要としますが、 '関数'を受け取ります

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の静的メソッド/クラスメソッドとしてではなく使用する必要があります。 documentationの例を参照してください。また

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) 

:コードは次のように見えるようになっています。

関連する問題