带有模拟项的python类()

带有模拟项的python类(),python,class,items,Python,Class,Items,以下是我的简单课程: class row(object): __slots__ = ("tan_id", "proc_name") def __init__( self, tan_id = "INDETERMINATE", proc_name = "INDETERMINATE" ): self.tan_id = tan_id

以下是我的简单课程:

 class row(object):
        __slots__ = ("tan_id", "proc_name")
        def __init__(
            self, 
            tan_id = "INDETERMINATE", 
            proc_name = "INDETERMINATE"
        ):
            self.tan_id = tan_id
            self.proc_name = proc_name
这门课以前是一本字典,但我遇到了严重的内存问题。稍后在我的代码中,我使用一个广义函数来循环如下:

 for key, val in row.items()

我不想改变。。。因此,我的问题是,如何在类中模拟item()函数,使其在现有for循环中无缝工作。

您可以简单地实现一个
items
方法,通过生成相同的键值对来模拟前面的
dict.items()
行为:

class row(object):
    # ...
    def items(self):
        # this is the iterator behaviour of 'items' (Py3) or 'iteritems' (Py2)
        yield 'tan_id', self.tan_id
        yield 'proc_name', self.proc_name
        # for the Py2 items behaviour, put these pairs into a list 
        # and return the list

    # Or, more generally:
    def items(self):
        for slot in self.__slots__:
            yield slot, getattr(self, slot)

您可以简单地实现一个
items
方法,该方法通过生成相同的键值对来模拟前面的
dict.items()
行为:

class row(object):
    # ...
    def items(self):
        # this is the iterator behaviour of 'items' (Py3) or 'iteritems' (Py2)
        yield 'tan_id', self.tan_id
        yield 'proc_name', self.proc_name
        # for the Py2 items behaviour, put these pairs into a list 
        # and return the list

    # Or, more generally:
    def items(self):
        for slot in self.__slots__:
            yield slot, getattr(self, slot)

对于您正在显示的行示例,之前的
项是什么?row={“tan_id”:tan_id,“proc_name”:proc_name}@gunslingor听起来您应该使用
namedtuple
。我同意,但它确实需要可静音。。。所以,答案是吃角子老虎。内存问题迫使进行此更改。对于您正在显示的行示例,之前的
项是什么?行={“tan_id”:tan_id,“proc_name”:proc_name}@gunslingor听起来您应该使用
namedtuple
。我同意,但它确实需要静音。。。所以,答案是吃角子老虎。内存问题迫使这种改变。第二个选项是理想的,如果它工作(测试…它应该),因为我有20个类似结构的类,但大多数都定义了20-50个变量。谢谢。第二个选项是理想的,如果它工作(测试…它应该),因为我有20个类似结构的类,但大多数都定义了20-50个变量。谢谢