如何在python中的类方法上应用装饰器

时间:2017-11-23 11:52:16

标签: python csv dictionary python-decorators

我正在尝试修改一个具有基于csv模块的方法的类。

数据是一个简单的三列csv文件,我想把它变成一个嵌套的字典列表。

我已经在SO question的帮助下成功了。

但是,我希望能够实现更通用的'load_data'方法,我可以使用装饰器来引入输出方法,以获取加载的csv的两列并输出为字典列表。< / p>

我尝试生成包装器函数和建议的csv_to_dict_dicts方法。

import csv

class AutoVivification(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
"""
def csv_decorator(func):
    def func_wrapper(self):
        for row in reader:
        return dict(self.data[row[0]][row[1]] = row[2] )
    return func_wrapper
"""


class CSV:
    def __init__(self):
        self.data = AutoVivification()

    def load_data(self, path):
        with open(path, encoding="utf-8") as f:
            self.path = path
            reader = csv.reader(f)
            for row in reader:
                self.data[row[0]][row[1]] = row[2]

    #@csv_decorator
    #def csv_to_dict_dicts(self):
    #    return self.load_data(path)


c = CSV()
c.load_data(path)

更新:

我尝试使用SO question

def csv_decorator(func):
    def func_wrapper(self):
        reader = func(self)
        for row in reader:
            self.data[row[0]][row[1]] = row[2]
    return func_wrapper


class CSV:
    def __init__(self):
        self.data = AutoVivification()

@csv_decorator
def load_data(self, path):
    with open(path, encoding="utf-8") as f:
        self.path = path
        reader = csv.reader(f)
        return reader

但是,我收到错误:

TypeError: func_wrapper() takes 1 positional argument but 2 were given

1 个答案:

答案 0 :(得分:0)

在上面的贡献者的指导下,我有一些有用的代码。

def csv_decorator(func):
    def func_wrapper(self, path):
        reader = func(self, path)
        for row in reader:
            self.data[row[0]][row[1]] = row[2]
    return func_wrapper


class CSV:
    def __init__(self):
        self.data = AutoVivification()

    @csv_decorator
    def load_data(self, path):
        f = open(path, encoding="utf-8")
        self.path = path
        reader = csv.reader(f)
        return reader