打印类功能

时间:2020-11-03 17:10:00

标签: python

我创建了一个类函数,但是当我打印所有打印结果时,它们如何粘在一起?

val a=2

此代码的打印结果为: pyomo2016Marcel35440.99

我想要的是这样的: pyomo,2016年,Marcel,354,40.99

类似的东西会更好

  • 标题:pyomo
  • 年份:2016
  • 作者:Marcel
  • 页数:354
  • 价格:40.99

预先感谢您的帮助!

5 个答案:

答案 0 :(得分:0)

您永远不会在字符串中添加任何换行符。您只需将它们串联在一起。在python 3.6及更高版本上尝试类似的事情:

function r = reminds(n,d)
    if n-d < 0
        r = n;
    else
        reminds(n-d,d)
    end
end

对于较旧的pyhton,这样的事情可能会正常工作:

def __str__(self):
    return f"{self._title}\n{self._year}\n{self._author}\n{self._page}\n{self._price}"

答案 1 :(得分:0)

如果您使用的是Python 3.6或更高版本,则可以使用f字符串来达到最佳效果:

def __str__(self):
    return f"{self._title}, {self._year}, {self._author}, {self._page}, {self._price}"

或者,对于“甚至更好”的版本(以PEP 8兼容的方式):

def __str__(self):
    return (
        f"Title: {self._title}\n"
        f"Year: {self._year}\n"
        f"Author: {self._author}\n"
        f"Page: {self._title}\n"
        f"Price: {self._price}"
    )

herePEP中了解有关f字符串的更多信息。

答案 2 :(得分:0)

像这样修改__str__

def __str__(self):
    return f"Title: {str(self._title)}\nYear: {str(self._year)}\nAuthor: {str(self._author)}\nPage: {str(self._page)}\nPrice: {str(self._price)}"

请注意,f字符串是python 3.6中引入的,否则请使用.format()

答案 3 :(得分:0)

您可以使用%s使用字符串嵌入

def __str__(self):
    return "%s, %s, %s, %s, %s" % (self._title, self._year, self._author, self._page, self._price)

答案 4 :(得分:0)

也许正在尝试print (b.__dict__)? 它返回一个参数字典:

{'_title': 'pyomo', '_year': 2016, '_author': 'Marcel', '_page': 354, '_price': 40.99}