For loop printing memory location of class instead of list

后端 未结 4 1305
不思量自难忘°
不思量自难忘° 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 01:58

    You have to define either a __str__ method or a __repr__ method for that:

    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 "".format(self.Make, self.Model, self.EngineSize, self.Price)
    
      def __str__(self):
        return "{0} {1}".format(self.Make, self.Model)
    

    In a nutshell,

    __repr__ is used if there's a need to display "raw" content of the object, it's the kind you see when you are displaying the list's contents, so if you have a list of cars, it would look like this:
    [, ]

    __str__ is used if you try to print the actual object, like print(TeslaCar) with TeslaCar being a TCar instance. It would give you something like "Tesla Model S".

提交回复
热议问题