描述符“getter”需要“属性”;对象但收到一个“函数”;
所以我在下面有一个 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'
任何人都可以解释此错误的含义吗?
So I have this code below for a Table object, and it has a property for 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)
When I try to import the file, I get the error:
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'
Can anybody explain what this error means?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我猜它相当于
TypeError: unbound method ... must be called with ... instance as first argument (got ... instance instead)
。要通过装饰器向属性添加setter,您必须使用.setter
作为属性对象的成员/方法,而不是作为property
的静态方法/类方法。代码应该如下所示:另请参阅文档中的示例。
I guess it's the equivalent to
TypeError: unbound method ... must be called with ... instance as first argument (got ... instance instead)
. To add a setter to a property via a decorator, you have to use.setter
as a member/method of the property object, not as a static method/classmethod ofproperty
. The code is supposed to look like this:Also see the example in the documentation.