【问题标题】:use the print () function on an Object to display an attribute [duplicate]在对象上使用 print() 函数来显示属性[重复]
【发布时间】:2021-11-19 18:06:00
【问题描述】:

当我使用打印功能时,我想打印关于我的对象的信息!

如果我打印 (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)

你能帮帮我吗?

【问题讨论】:

标签: python python-3.x


【解决方案1】:

您需要为该类定义一个__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 + ")"

【讨论】:

    【解决方案2】:

    您应该在您的对象中实现__str__ 方法,这是您的类的字符串表示形式。

    【讨论】:

      猜你喜欢
      • 2018-06-28
      • 2017-09-13
      • 1970-01-01
      • 2017-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多