For loop printing memory location of class instead of list

后端 未结 4 1304
不思量自难忘°
不思量自难忘° 2021-01-28 01:24

I have some code which seems to print [<__main__.TCar object at 0x0245C1B0>] but I want it to print the actual contents of the list.

class TCa         


        
4条回答
  •  [愿得一人]
    2021-01-28 02:11

    You can either override __str__ or __repr__ like this:

    class TCar():
      def __init__(self, Make, Model, EngineSize, Price):
        self.Make = str(Make)
        self.Model = str(Model)
        self.EngineSize = float(EngineSize)
        self.Price = float(Price)
    
      def __repr__(self):
        return "{Make}-{Model} (v{EngineSize}/{Price}$)".format(**self.__dict__)
    
    Garage = [TCar("Audi", "TT", "8", "80000")]
    print(Garage)
    # [Audi-TT (v8.0/80000.0$)]
    

    Also you might want to check out this question about __str__ vs. __repr__.

提交回复
热议问题