Python 为两个不同长度的实例变量定义

Python 为两个不同长度的实例变量定义,python,oop,Python,Oop,我有以下课程。它有两个以数组表示的实例变量。它们不一定具有相同的长度: class A(object): def __init__(self, input): self.input = [] for data in input: self.input.append(data) self.other_information = [] self.input和self.other\u信息都将包含来自其他类的对象。在我的

我有以下课程。它有两个以数组表示的实例变量。它们不一定具有相同的长度:

class A(object):

    def __init__(self, input):
        self.input = []
        for data in input:
            self.input.append(data)
        self.other_information = []

self.input
self.other\u信息
都将包含来自其他类的对象。在我的
\uuuu str\uuuu
方法中,我需要对它们进行迭代。定义一个
\uuuuu iter\uuuu
方法来处理一个带有单个数组的实例变量的对象是没有问题的。如果两个数组具有相同的长度,这不会是一个问题,但是我可以使用一个
\uuuu iter\uuuu
方法来迭代
\uu str\uuu
方法中具有不同长度的两个实例变量吗?我已经在这里看到了非面向对象的帖子,但是类似这样的帖子呢?

您可以使用itertools.chain()顺序迭代两个数组

import itertools


class A(object):
    def __init__(self, input):
        self.input = []
        for data in input:
            self.input.append(data)
        self.other_information = list(range(5))

    def __iter__(self):
        return itertools.chain(self.input, self.other_information)


a = A(['a', 'b', 'c'])

for i in a:
    print(i)

# a
# b
# c
# 0
# 1
# 2
# 3
# 4
您还可以使用“收益率”。结果是一样的

def __iter__(self):
    yield from self.input
    yield from self.other_information

您希望输出是什么样子的?有很多方法可以迭代两件事:压缩、交错、一个接一个等等。你想使用哪一种?按顺序。一个数组,然后是另一个数组。真的不确定我在oop环境中的选择。在功能上下文中,我可以做任何事情。这似乎不一样。那么你看;不清楚为什么长度是相关的。或者只写函数版本,Python是多范式的。