2011-09-10 46 views
5

Vì vậy, tôi có mã này dưới đây cho một đối tượng Bảng, và nó có một tài sản cho tên trường.mô tả 'getter' yêu cầu một đối tượng 'tài sản' nhưng nhận được một 'chức năng'

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) 

Khi tôi cố gắng nhập khẩu các tập tin, tôi nhận được lỗi:

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' 

Ai có thể giải thích những gì lỗi này có nghĩa là?

Trả lời

16

Tôi đoán nó tương đương với TypeError: unbound method ... must be called with ... instance as first argument (got ... instance instead). Để thêm một bộ chuyển đổi vào một thuộc tính thông qua một trình trang trí, bạn phải sử dụng .setter làm một thành viên/phương thức của đối tượng thuộc tính, không phải là một phương thức/lớp học tĩnh của property. Mã được cho là giống như sau:

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) 

Cũng xem ví dụ trong documentation.

Các vấn đề liên quan