繁体   English   中英

如何为我的 class Book 打印如下所示的输出?

[英]how do i print outputs like below for my class Book?

创建一个名为 Book 的 class。

调用时,description() 应返回描述。

这是 Book 应该如何工作的示例。

book_one = Book("1984", "George Orwell", 6.99)

打印(book_one.description())

应该打印:

书名:1984

作者:乔治·奥威尔

价格:6.99 英镑

book_one = Book("1984", "George Orwell", 6.99, no_pages=328)

打印(book_one.description())

应该打印:

书名:1984

作者:乔治·奥威尔

价格:6.99 英镑

页数:328

book_one = Book("1984", "George Orwell", 6.99, year=1949)

打印(book_one.description())

应该打印:

书名:1984

作者:乔治·奥威尔

价格:6.99 英镑

出版年份:1949

book_one = Book("1984", "George Orwell", 6.99, no_pages=328, year=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()`
def description(self):
  return f"""Title: {self.title}

Author: {self.author}

Price: £{self.price}"""

更 Pythonic 的方法是覆盖 __str__ dunder function。这样你就不会显式调用 function 来以你需要的格式获取 class 内容。 print() function 将在它正在处理的 object 中寻找 __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))

Output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM