如何在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()
那么如何列这样一个单子呢?
只需创建一个列表。
只需像在Python中创建任何其他东西的数组一样执行它?
如果您需要它作为一个类,比如您的c++示例,您可以这样做:
它看起来像:
你也可以直接附加附加的:
实现
__repr__
或__str__
有助于更好地打印。相关问题 更多 >
编程相关推荐