python class 含模拟物品()
python class with simulated items()
这是我的简单 class:
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
这个class曾经是字典,但我运行陷入了严重的记忆问题。后来在我的代码中,我使用了一个通用函数来像这样循环:
for key, val in row.items()
我不想改变...所以我的问题是,如何在 class 中模拟 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)
这是我的简单 class:
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
这个class曾经是字典,但我运行陷入了严重的记忆问题。后来在我的代码中,我使用了一个通用函数来像这样循环:
for key, val in row.items()
我不想改变...所以我的问题是,如何在 class 中模拟 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)