Python 3.4中的类对象数组

2024-09-29 17:21:54 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在Python3.4中声明类对象数组?在C++中,我可以很容易地做到:

class Segment
{
public:

    long int left, right;

    Segment()
    {
        left = 0;
        right = 0;
    }

    void show_all()
    {
        std::cout << left << " " << right << endl;
    }
};

int main()
{
    const int MaxN = 10;
    Segment segment[MaxN];

    for(int i = 0; i < MaxN; i++)
    {
        std::cin >> segment[i].left;
        std::cin >> segment[i].right;
    }
}
Python中的p>几乎相同,但无法找到一种方法来创建类的对象列表并像C++一样迭代它。

class Segment:

    def __init__(self):
        self.left = 0
        self.right = 0

    def show_all(self):
        print(self.left, self.right)

segment = Segment()

那么如何列这样一个单子呢?


Tags: 对象selfright声明defshowsegmentall
3条回答

只需创建一个列表。

segments = [Segment() for i in range(MaxN)]
for seg in segments:
    seg.left = input()
    seg.right = input()

只需像在Python中创建任何其他东西的数组一样执行它?

mylist = []
for i in range(0,10):
    mylist.append(Segment())

如果您需要它作为一个类,比如您的c++示例,您可以这样做:

class Single():
    def __init__(self, left, right):
        self.left=left
        self.right=right

class CollectionOfSingles():
    def __init__(self, SingleObjects):
        self.singles = list(SingleObjects) #the cast here is to indicate that some checks would be nice

它看起来像:

>>> a = Single("a", "b")
>>> b = Single("c", "d")
>>> c = Single("e", "f")
>>> objectarray = CollectionOfSingles([a, b, c])
>>> objectarray.singles
[<__main__.Single object at 0x00000000034F7D68>, <__main__.Single object at 0x00000000035592E8>, <__main__.Single object at 0x0000000003786588>]

你也可以直接附加附加的:

>>> objectarray.singles.append(Single("g", "d"))
>>> objectarray.singles
[<__main__.Single object at 0x00000000034F7D68>, <__main__.Single object at 0x00000000035592E8>, <__main__.Single object at 0x0000000003786588>, <__main__.Single object at 0x0000000003786828>]

实现__repr____str__有助于更好地打印。

相关问题 更多 >

    热门问题