Home > Back-end >  How to print out a list used as a class attribute or instance attribute
How to print out a list used as a class attribute or instance attribute

Time:02-20

I've been playing with this for a little while now and can't see to figure it out. I have a simple class and want to use a list as either a shared class attribute or even just a instance attribute. Obviously, at some point it would be nice to see what is in this list, but all I can get to return is the object info (<__main__.Testclass instance at 0x7ff2a18c>). I know that I need to override the __repr__ or __str__ methods, but I'm definitely not doing it correctly.

class TestClass():
   
   someList = []

   def __init__(self):
      self.someOtherList = []

   def addToList(self, data):
      self.someOtherList.append(data)
      TestClass.someList.append(data)

   def __repr__(self):
      #maybe a loop here? I've tried returning list comprehensions and everything. 
      pass

test = TestClass()
test.addToList(1)
test.addToList(2)
test.addToList(3)

print(test.someList)
print(test.someOtherList)

I just want to see either [1,2,3] or 1 2 3 (hopefully choose either one).

CodePudding user response:

With test.someList and test.someOtherList, you can already see what is inside those lists...

If you want to see those lists when printing the test object, you can either implement __str__ or __repr__ and delegate the representation of the instance to one of those. (either someList or someOtherList)

    def __repr__(self):
        return str(self.someOtherList)

Now whenever you print your test object, it shows the representation of self.someOtherList.

class TestClass:
    someList = []

    def __init__(self):
        self.someOtherList = []

    def addToList(self, data):
        self.someOtherList.append(data)
        TestClass.someList.append(data)

    def __repr__(self):
        return str(self.someOtherList)


test = TestClass()
test.addToList(1)
test.addToList(2)
test.addToList(3)

print(test)

output

[1, 2, 3]
  • Related