描述符'getter'需要'property'对象但是收到'function'

时间:2011-09-10 20:55:41

标签: python properties decorator setter

所以我在下面有一个Table对象的代码,它有一个fieldnames属性。

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'

有人可以解释这个错误的含义吗?

1 个答案:

答案 0 :(得分:18)

我猜这相当于TypeError: unbound method ... must be called with ... instance as first argument (got ... instance instead)。要通过装饰器向属性添加setter,必须使用.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中的示例。