当我使用打印函数时,我想打印关于我的对象的信息!
如果我执行print(my_product),它会显示Product(name = the_name)。
我的类:
class Product:
def __init__(self, name = ""):
self._name = name
@property
def name(self):
return self._name
例如:
my_product = Product("Computer")
print(my_product)
#Product(name=Computer)
你能帮我一下吗?
您需要为类定义一个__str__
函数,如下所示:
class Product:
def __init__(self, name = ""):
self._name = name
@property
def name(self):
return self._name
def __str__(self):
return " Product(name = " + self._name + ")"
你应该在你的对象中实现__str__
方法,它是你的类的字符串表示。