繁体   English   中英

如何将装饰器应用于python中的类方法

[英]How apply decorator on a class method in python

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

数据是一个简单的三列csv文件,我想将其转换为字典的嵌套列表。

我已经通过这个问题解决了这个问题

但是,我希望能够实现一种更通用的“ load_data”方法,我可以使用装饰器引入一些方法来输出以获取两列已加载的csv的方法,并以字典列表的形式输出。

我尝试产生包装函数和建议的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问题

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

在以上贡献者的指导下,我得到了一些有效的代码。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM