[英]How apply decorator on a class method in python
I'm trying to modify a class which has methods based on the csv module. 我正在尝试修改具有基于csv模块的方法的类。
The data is a simple three-column csv file which I wanted to turn into a nested list of dictionaries. 数据是一个简单的三列csv文件,我想将其转换为字典的嵌套列表。
I've managed to that with the help of this SO question . 我已经通过这个问题解决了这个问题 。
However, I'd like to be able to implement a more general 'load_data' method, one which I could use decorators to introduce methods to output to take two columns of a loaded csv and output as a list of dictionaries. 但是,我希望能够实现一种更通用的“ load_data”方法,我可以使用装饰器引入一些方法来输出以获取两列已加载的csv的方法,并以字典列表的形式输出。
My attempt to produce the wrapper function and proposed csv_to_dict_dicts method are commented out. 我尝试产生包装函数和建议的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)
UPDATE: 更新:
I've tried using SO question thus: 我已经尝试过使用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
However, I receive the error: 但是,我收到错误消息:
TypeError: func_wrapper() takes 1 positional argument but 2 were given
With the guidance of the contributors above, I've got some code that works. 在以上贡献者的指导下,我得到了一些有效的代码。
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.