如何调用Book通过info()方法输出
时间: 2023-06-09 16:05:59 浏览: 58
要调用Book的info()方法输出信息,你需要先创建一个Book对象,并传递相应的参数,例如:
```python
class Book:
def __init__(self, title, author, year):
self.title = title
self.author = author
self.year = year
def info(self):
print(f"{self.title} by {self.author} published in {self.year}")
book = Book("The Hitchhiker's Guide to the Galaxy", "Douglas Adams", 1979)
book.info() # 输出: The Hitchhiker's Guide to the Galaxy by Douglas Adams published in 1979
```
在这个例子中,我们先定义了一个Book类,并且在类的初始化方法中定义了title、author和year这三个属性。在info()方法中,我们使用了f-string(格式化字符串)来输出书籍的信息。最后,我们创建了一个名为book的Book对象,并调用它的info()方法来输出信息。
相关问题
请用Book实例化一个python_book对象,并调用info()方法,输出信息
好的,我可以使用如下代码实例化一个python_book对象,并调用它的info()方法输出信息:
```python
class Book:
def __init__(self, title, author, publisher, year):
self.title = title
self.author = author
self.publisher = publisher
self.year = year
def info(self):
print(f"Title: {self.title}")
print(f"Author: {self.author}")
print(f"Publisher: {self.publisher}")
print(f"Year: {self.year}")
python_book = Book("Learning Python", "Mark Lutz", "O'Reilly Media", 2013)
python_book.info()
```
输出的信息为:
```
Title: Learning Python
Author: Mark Lutz
Publisher: O'Reilly Media
Year: 2013
```
定义一个TextBook类,从Book类继承。请增加属性courseware和exercise,并重载info()方法,增加courseware和exercise信息输出。请实例化一个python_textbook对象,并调用info()方法,输出信息
好的,我已经了解了你的要求。下面是定义TextBook类的代码,包括从Book类继承、新增属性和重载info()方法:
```python
class Book:
def __init__(self, title, author, publisher, price):
self.title = title
self.author = author
self.publisher = publisher
self.price = price
def info(self):
print(f"《{self.title}》是由{self.author}撰写,由{self.publisher}出版,售价{self.price}元。")
class TextBook(Book):
def __init__(self, title, author, publisher, price, courseware, exercise):
super().__init__(title, author, publisher, price)
self.courseware = courseware
self.exercise = exercise
def info(self):
super().info()
print(f"附带课件{self.courseware}和习题{self.exercise}。")
```
接下来,我们可以实例化一个python_textbook对象,并调用info()方法输出信息:
```python
python_textbook = TextBook("Python编程入门", "张三", "人民邮电出版社", 49.9, "Python学习视频", "Python编程题库")
python_textbook.info()
```
输出结果为:
```
《Python编程入门》是由张三撰写,由人民邮电出版社出版,售价49.9元。
附带课件Python学习视频和习题Python编程题库。
```