Home > Enterprise >  use the print () function on an Object to display an attribute [duplicate]
use the print () function on an Object to display an attribute [duplicate]

Time:09-28

I want print information about my Object when I use print function!

if I do print( my_product ) it displays Product(name = the_name).

My Class:

class Product:
    def __init__(self, name = ""):
    self._name = name


    @property
    def name(self):
        return self._name

e.g.:

my_product = Product("Computer")
print(my_product)
#Product(name=Computer)

Can you help me please ?

CodePudding user response:

You need to define a __str__ function for the class like so:

class Product:
    def __init__(self, name = ""):
        self._name = name


    @property
    def name(self):
        return self._name

    def __str__(self):
        return " Product(name = "   self._name   ")"

CodePudding user response:

You should implement the __str__ method in your object, which is the string representation of your class.

  • Related