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?
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.setteras 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.