Python 将类应用于列表中的项

Python 将类应用于列表中的项,python,Python,我试图做的是允许向函数提供任意数量的属性。此函数将处理基于这些属性创建类的操作。然后,我有另一个函数,它将处理从文本文件导入数据,将生成的类应用于每个项,并将其添加到列表中。下面是我所拥有的 def create_class(attributes): class classObject: def __init__(self, **attributes): for attr in attributes.keys():

我试图做的是允许向函数提供任意数量的属性。此函数将处理基于这些属性创建类的操作。然后,我有另一个函数,它将处理从文本文件导入数据,将生成的类应用于每个项,并将其添加到列表中。下面是我所拥有的

def create_class(attributes):
    class classObject:
        def __init__(self, **attributes):
            for attr in attributes.keys():
                self.__dict__[attr] = attributes[attr]

    return classObject

def file_to_list(file, attributes):
    classObject = create_class(attributes)

    with open(file, "r") as f:
        var = []

        for line in f.readlines():
            var.append(classObject(line))

    return var

data = file_to_list("file.txt", ["propA", "propB"])
问题在于我如何尝试将项目添加到列表中。通常情况下,我不会有任何问题,但我相信我创建类的方式会导致我通常如何做的问题

文件“File.py”,第17行,在文件列表中 var.append(类对象(行)) TypeError:init()接受1个位置参数,但给出了2个

如何循环遍历类的每个属性,以便为每个属性设置值并将其添加到列表中

更新: 下面是file.txt的示例

1A,1B
2A,2B
3A,3B

首先,为什么不为此使用
类型
?它是默认的元类,即创建类对象的可调用元类。类dict将是第三个参数,它使以编程方式创建变得容易

type(name, (), attributes)
(您可能不需要任何基类,但这正是第二个参数的目的。)


其次,您的
\uuuu init\uuuu
似乎不接受str,这是您可以从
readlines()
获得的唯一内容。它只接受self(隐含)和关键字参数


您也许可以将
str转换为dict(但这取决于其中的内容),然后将dict用作KWARG,如
classObject(**kwargs)
,但是,首先在
\uuuu init\uuuu
方法中用星号声明它可能没有意义。

看起来您的类生成是错误的。您似乎希望能够执行以下操作:

Cls = create_class(["some", "attributes", "go", "here"])
并最终得到一个类对象,该类对象如下所示:

class Cls(object):
    def __init__(self, some, attributes, go, here):
        self.some = some
        self.attributes = attributes
        self.go = go
        self.here = here
但实际上您所做的是创建一个类,该类接受字典,并给出字典点语法

>>> obj = Cls({"different": "attributes", "go": "here"})
>>> obj.different
"attributes"
>>> obj.go
"here"
您可以通过以下方式实现前者:

def create_class(attributes: typing.List[str]):
    class gen_class(object):
        def __init__(self, *args):
            if len(args) != len(attributes):
                # how do you handle the case where the caller specifies fewer or more
                # arguments than the generated class expects? I would throw a...
                raise ValueError(f"Wrong number of arguments (expected {len(attributes)}, got {len(args)}.")
            for attr, value in zip(attributes, args):
                setattr(self, attr, value)
然后您应该能够使用
csv.reader
读取文件并实例化这些类

import csv

CSV_Cls = create_class(["propA", "propB"])

with open(file) as f:
    reader = csv.reader(f)
    data = [CSV_Cls(*row) for row in reader]

然而,在这里,编写自己的代码生成器来生成该类似乎是错误的选择。为什么不改用
collections.namedtuple

from collections import namedtuple

CSV_Cls = namedtuple("CSV_Cls", "propA propB")

with open(file) as f:
    reader = csv.reader(f)
    data = [CSV_Cls(*row) for row in reader]

这个stdlib代码已经编写好了,可以正常工作(并且经过了大量测试),并且不会意外地引入错误。选择类的唯一原因是,如果您需要将某些行为与数据紧密耦合,或者如果您需要可变的数据结构,

行是什么样子?从类中的字符串创建类的类方法可能是您正在寻找的解决方案。给定该文件,你希望你的类看起来像什么?
namedtuple
确实创建了一个类。但我仍然不确定作者是否想要这样的类。@gilch是的,我在代码块后面的文本中提到了这一点,但我应该更明确一些。我认为一个
namedtuple
将是一个问题。
create\u class
函数本身的原因是,当我想逐个添加属性值时。我会提供类的属性来构建类,但不会在其中创建任何对象。在确定这些值时,我会将它们添加到类对象中。一旦确定了所有的值,我就将类对象添加到一个列表中。您提供的代码似乎不适合我。在使用第二个和第三个到最后一个代码块时,我不断得到以下信息<代码>文件“File.py”,第20行,在
数据=[CSV_Cls(*row)中,用于读取器中的行]
TypeError:“NoneType”对象不可调用
Nevermind。我明白问题所在。它似乎按照我想要的方式工作。对于名为tuple的
,代码显然更干净。不幸的是,我需要一个可变的数据结构。感谢您的详细解释和代码示例!