簡體   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