从列表中创建一个__init__类(make a class __init__ from a list)
我有这样的东西,硬编码:
class csv_row: def __init__(self, name, time, more_stuff): self.name = name self.time = time self.more_stuff = more_stuff
这个类是csv行的表示。 我想要做的是使它更通用,并抓住csv文件的头部并使用它以与此列表相同的方式初始化它。 像这样的东西:
class csv_row: def __init__(self, list_of_attrs): for column in list_of_attrs: # initialize a self.variable with the same name as the column
例如,csv的标题是
[name, time, something]
。 传递的__init__
将初始化为:self.name = name self.time = time self.something = something
如何才能做到这一点?
I have something like this, hardcoded:
class csv_row: def __init__(self, name, time, more_stuff): self.name = name self.time = time self.more_stuff = more_stuff
this class is the representation of a csv row. What I want to do is make this more generic, and grab the head of the csv file and use it to initialize it in the same way as this list. Something like so:
class csv_row: def __init__(self, list_of_attrs): for column in list_of_attrs: # initialize a self.variable with the same name as the column
for example, the header for a csv is
[name, time, something]
. The__init__
, when passed that, will initialize with:self.name = name self.time = time self.something = something
How can this be done?
原文:https://stackoverflow.com/questions/23275587
最满意答案
已经有几个设施来处理这样的事情。 没有必要重新发明轮子:
namedtuple
from collections import namedtuple headers = ["one", "two", "three"] CustomRow = namedtuple("CustomRow", headers) a_row = CustomRow(1, 2, 3) a_row.one == 1 # True a_row.two == 2 # True a_row.three == 3 # True
csv.DictWriter
和csv.DictReader
import csv with open("my_file.csv", "rb") as f: reader = csv.DictReader(f, ["one", "two", "three"]) for line in reader: print line["one"] # prints the 1st column print line["two"] # etc. print line["three"] # etc., etc.
There already exist several facilities for dealing with something like this. There is no need to reinvent the wheel:
namedtuple
from collections import namedtuple headers = ["one", "two", "three"] CustomRow = namedtuple("CustomRow", headers) a_row = CustomRow(1, 2, 3) a_row.one == 1 # True a_row.two == 2 # True a_row.three == 3 # True
csv.DictWriter
andcsv.DictReader
import csv with open("my_file.csv", "rb") as f: reader = csv.DictReader(f, ["one", "two", "three"]) for line in reader: print line["one"] # prints the 1st column print line["two"] # etc. print line["three"] # etc., etc.