0

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 ?

Kardier
  • 77
  • 8
  • 3
    Duplicate of [Does Python have a toString() equivalent, and can I convert a db.Model element to String?](https://stackoverflow.com/questions/16768302/does-python-have-a-tostring-equivalent-and-can-i-convert-a-db-model-element-t) – esqew Sep 27 '21 at 15:22
  • 2
    What, exactly, do you want the output to be? – John Gordon Sep 27 '21 at 15:22

2 Answers2

1

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 + ")"
BTables
  • 4,413
  • 2
  • 11
  • 30
0

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

Isy89
  • 179
  • 8