python 我如何打印输出像下面为我的类书?

ffscu2ro  于 2023-01-16  发布在  Python
关注(0)|答案(2)|浏览(161)

创建一个名为Book的类。
当调用时,description()应该返回描述。
下面是Book应该如何工作的一个示例。
book_one =书("1984","乔治·奥威尔",6. 99)
打印(book_one.描述())
应打印:
标题:1984年
作者:乔治·奥威尔
售价:6.99英镑
第一本书=书("1984","乔治·奥威尔",6. 99,页码= 328)
打印(book_one.描述())
应打印:
标题:1984年
作者:乔治·奥威尔
售价:6.99英镑
页数:328
book_one =图书("1984","乔治·奥威尔",6.99,年份= 1949)
打印(book_one.描述())
应打印:
标题:1984年
作者:乔治·奥威尔
售价:6.99英镑
发表年份:1949
第一本书=书("1984","乔治·奥威尔",6.99,页码= 328,年份= 1949)
print(book_one. description())应打印:
标题:1984年
作者:乔治·奥威尔
售价:6.99英镑
发表年份:1949
页数:328

`class Book:

 def __init__(self, title, author, price,no_pages = None, year = None):

  self.title = title

  self.author = author

  self.price = price

  self.no_pages = no_pages

  self.year = year

 def description(self):

  print(f"Title: {self.title}")

  print(f"Author: {self.author}")

  print(f"Price: £{self.price}")

  print(f"No. of Pages: {self.no_pages}")

  print(f"Year: {self.year}")

  return

if __name__ == "__main__":

 book_one = Book("1984", "George Orwell", 6.99,328,year = 1949)
 book_one.description()`
qlfbtfca

qlfbtfca1#

def description(self):
  return f"""Title: {self.title}

Author: {self.author}

Price: £{self.price}"""
bqujaahr

bqujaahr2#

更像Python的方法是重写__str__dunder函数,这样你就不用显式调用函数来获取你需要的格式的类内容,* print()* 函数会在它处理的对象中寻找__str__的实现,如果没有,它会寻找__repr__
大概是这样的

class Book:
    def __init__(self, title, author, price, no_pages=None, year=None):
        self._title = title
        self._author = author
        self._price = float(price)
        self._no_pages = no_pages
        self._year = year
    def __str__(self):
        parts = [
            f'Title: {self._title}',
            f'Author: {self._author}',
            f'Price: £{self._price:.2f}'
        ]
        if self._year is not None:
            parts.append(f'Year Published: {self._year}')
        if self._no_pages is not None:
            parts.append(f'No. of Pages: {self._no_pages}')
        return '\n'.join(parts)

print(Book("1984", "George Orwell", 6.99), '\n')
print(Book("1984", "George Orwell", 6.99, no_pages=328), '\n')
print(Book("1984", "George Orwell", 6.99, year=1949), '\n')
print(Book("1984", "George Orwell", 6.99, no_pages=328, year=1949))
    • 输出:**
Title: 1984
Author: George Orwell
Price: £6.99 

Title: 1984
Author: George Orwell
Price: £6.99
No. of Pages: 328 

Title: 1984
Author: George Orwell
Price: £6.99
Year Published: 1949 

Title: 1984
Author: George Orwell
Price: £6.99
Year Published: 1949
No. of Pages: 328

相关问题