[英]How do you create multiple objects from a class in Python using an equivalent algorithm to this one in Java?
I've written a piece of code in Java to create multiple objects for a problem solving exercise.我在 Java 中编写了一段代码来创建多个对象来解决问题。 This worked successfully, but I'm now trying to write it in Python and can't work out how to do it.
这很成功,但我现在正试图用 Python 编写它,但不知道该怎么做。 I want to have a list of objects, each with unique values, that I can use in the rest of my code.
我想要一个对象列表,每个对象都有唯一的值,我可以在我的代码的 rest 中使用它。
Here's my Java code:这是我的 Java 代码:
public void createSquares() {
int square = 0;
int count = 0;
for (int r=1; r<10; r++) {
for (int c=1; c<10; c++) {
if (r<4 && c<4) {
square = 1;
}
else if (r<4 && c>3 && c<7){
square = 2;
}
else if (r<4 && c>6){
square = 3;
}
else if (r>3 && r<7 && c<4){
square = 4;
}
else if (r>3 && r<7 && c>3 && c<7){
square = 5;
}
else if (r>3 && r<7 && c>6){
square = 6;
}
else if (r>6 && c<4){
square = 7;
}
else if (r>6 && c>3 && c<7){
square = 8;
}
else if (r>6 && c>6){
square = 9;
}
Square s = new Square(r, c, square, count); //How does this work in Python?
sList.add(count, s);
count++;
}
}
}
In python, constructors (in a method called __init__
) accept a parameter called self
representing the object itself, before any other parameter.在 python 中,构造函数(在名为
__init__
的方法中)在任何其他参数之前接受一个名为self
的参数,该参数表示 object 本身。
class Square:
def __init__(self, r, c, square, count): # Create the constructor, accepting 4 parameters
self.r = r
self.c = c
self.square = square
self.count = count
And in your main loop:在你的主循环中:
s = Square(r, c, square, count) # Notice there is no "self" here, and the keyword "new" is not used
list.append(s) # Python lists use "append" and not "add"
count += 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.