Results 1 to 2 of 2

Thread: Creating a list of object in Pyton

  1. #1
    Join Date
    Oct 2018
    Beans
    1

    Creating a list of object in Pyton

    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))
    Last edited by slickymaster; October 16th, 2018 at 10:37 AM. Reason: code tags

  2. #2
    Join Date
    Aug 2010
    Location
    Lancs, United Kingdom
    Beans
    1,588
    Distro
    Ubuntu Mate 16.04 Xenial Xerus

    Re: Creating a list of object in Pyton

    Welcome to the forums. It would help greatly if you could use code tags when posting python code in order to preserve indentation.

    Your problem is that this line:
    Code:
      listOfObjects = []
    is inside the for loop. So on each pass through the loop you empty out the list and append 1 item. The above line should instead appear before the for loop, like this:
    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!")
    
    
    listOfObjects = []
    for i in range(3):
      listOfObjects.append(newObject("object"+str(i+1)))
      newObject.status()
    
    print (len(listOfObjects))

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •