For loop printing memory location of class instead of list

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

    print the attribute one by one rather than printing garange once: print(self.attribute).Note that the attribute in the code is an instance of the object

    0 讨论(0)
  • 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 "<Car {0} {1} {2} {3}>".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:
    [<Car Tesla Model S 500bhp $100000>, <Car Smart Fortwo 80bhp $5000>]

    __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".

    0 讨论(0)
  • 2021-01-28 02:03

    You have a list of objects here. Add something like:-

    def __str__(self):
      print self.Make, self.Model, self.EngineSize, self.Price
    

    This would print the value of all attributes of object. Or you can modify the function as per your behavior requirement.

    0 讨论(0)
  • 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__.

    0 讨论(0)
提交回复
热议问题