Python 实现一个类,表示一个简单的电子书
我们将创建一个简单的电子书类 EBook
,该类包含书名、作者、页数和当前页码等属性。我们还将实现一些方法,如翻页、获取当前页内容等。
实例
class EBook:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
self.current_page = 1
def next_page(self):
if self.current_page 1:
self.current_page -= 1
else:
print("You are already at the beginning of the book.")
def get_current_page_content(self):
return f"Page {self.current_page} of {self.pages}"
def __str__(self):
return f"'{self.title}' by {self.author}, {self.pages} pages"
# 示例使用
book = EBook("Python Programming", "John Doe", 300)
print(book)
print(book.get_current_page_content())
book.next_page()
print(book.get_current_page_content())
book.previous_page()
print(book.get_current_page_content())
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
self.current_page = 1
def next_page(self):
if self.current_page 1:
self.current_page -= 1
else:
print("You are already at the beginning of the book.")
def get_current_page_content(self):
return f"Page {self.current_page} of {self.pages}"
def __str__(self):
return f"'{self.title}' by {self.author}, {self.pages} pages"
# 示例使用
book = EBook("Python Programming", "John Doe", 300)
print(book)
print(book.get_current_page_content())
book.next_page()
print(book.get_current_page_content())
book.previous_page()
print(book.get_current_page_content())
代码解析:
__init__
方法:初始化电子书的属性,包括书名、作者、总页数和当前页码。next_page
方法:将当前页码加1,如果已经是最后一页,则提示用户已到达书的末尾。previous_page
方法:将当前页码减1,如果已经是第一页,则提示用户已在书的开头。get_current_page_content
方法:返回当前页码的内容。__str__
方法:返回电子书的基本信息,包括书名、作者和总页数。
输出结果:
'Python Programming' by John Doe, 300 pages Page 1 of 300 Page 2 of 300 Page 1 of 300