gpt4 book ai didi

python - 描述符 'getter' 需要一个 'property' 对象,但收到一个 'function'

转载 作者:太空狗 更新时间:2023-10-29 19:35:32 25 4
gpt4 key购买 nike

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

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'

谁能解释一下这个错误是什么意思?

最佳答案

我想这等同于 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 中的示例.

关于python - 描述符 'getter' 需要一个 'property' 对象,但收到一个 'function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7374666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com