I have created a basic class and each new object that I create, I want to append it to a list. When I print the length of the list, the output is 1, not 3. Based on the output generated within the for loop, I am generating 3 different objects. Any clues as to why the listOfObjects has length 1?
Code:
class newObject (object):
total = 0
@staticmethod
def status():
print("\nThe total number of new objects is", newObject.total)
def __init__(self, name):
print("A new object has been created!")
self.name = name
newObject.total += 1
#main
print("Accessing the class attribute newObject.total:", end=" ")
print(newObject.total)
print("\nCreating objects!")
for i in range(3):
listOfObjects = []
listOfObjects.append(newObject("object"+str(i+1)))
newObject.status()
print (len(listOfObjects))
Bookmarks