简体   繁体   中英

How to print out a list used as a class attribute or instance attribute

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).

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM