Home > other >  How to create multiple objects correctly?
How to create multiple objects correctly?

Time:10-22

In accordance with the following code, the output of the whole is 9,
And want is every cycle to create an object to accommodate different data, ask how can create a new object in each loop?
 

The class Comment () :
Def __init__ (self) :
Pass


Def lop () :
Comments=[]
For I in range (10) :
Comment=the comment
The comment. Independence idx=I
Comments. Append (comment)

The return comments


If __name__=="__main__ ':
Comments=lop ()

# print (len (comments))

For independence idx in range (len (comments) :
Print (comments) [r]. Independence idx independence idx)


CodePudding user response:

Why not add parentheses, instantiation of the object can be referenced again? !

The
refer to the original poster jarodzhao response:
in accordance with the following code, output of all nine,
And want is every cycle to create an object to accommodate different data, ask how can create a new object in each loop?
 

The class Comment () :
Def __init__ (self) :
Pass


Def lop () :
Comments=[]
For I in range (10) :
Comment=the comment (#) parentheses here, is to create a new instance
The comment. Independence idx=I
Comments. Append (comment)

The return comments


If __name__=="__main__ ':
Comments=lop ()

# print (len (comments))

For independence idx in range (len (comments) :
Print (comments) [r]. Independence idx independence idx)


CodePudding user response:

Line 9:
 
Comment=the comment (#) instantiated need to add brackets


You didn't add parentheses, assignment, the comment is equivalent to the comment, equal to give the comment to add static attribute independence idx
 
The Comment. Independence idx=I


So you append the Comment is a class object, not its instance, independence idx is the Comment of static properties, the final assignment

CodePudding user response:

 
For independence idx in range (len (comments) :
Print (comments) [r]. Independence idx independence idx)

Look at this writing, is to turn to other language

CodePudding user response:

 

The class Comment () :
Def __init__ (self) :
Pass


Def lop () :
Comments=[]
For I in range (10) :
Comment=the comment ()
The comment. Independence idx=I
Comments. Append (comment)

The return comments


If __name__=="__main__ ':
Comments=lop ()

# print (len (comments))

For independence idx in range (len (comments) :
Print (comments) [r]. Independence idx independence idx)


  • Related