Respuesta :
Answer:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
self.tableOfContents = ''
self.nextPage = 1
def addChapter(self, title, numberOfPages):
self.tableOfContents += '\n{}...{}'.format(title, self.nextPage)
self.nextPage += numberOfPages
def getPages(self):
return self.nextPage
def getTableOfContents(self):
return self.tableOfContents
def toString(self):
return '{}\n{}'.format(self.title, self.author)
book1 = Book('Learning Programming with Python', 'Andrew')
Explanation:
NB: Please do not ignore the way the code snippet text was indented. This is intentional and the Python interpreter uses spaces/indentation to mark the start and end of blocks of code
Python is a language that supports Object Oriented Programming(OOP). To define a constructor in a Python class, we make use of the syntax:
def __init__(self)
When an object is instantiated from the class, the __init__ method which acts as the constructor is the first method that is called. This method basically is where initialisation occurs. Consider this line of code in the snippet above:
book1 = Book('Learning Programming with Python', 'Andrew'). Here, book1 is an object of the class Book and during the creation of this instance, the title attribute was Learning Programming with Python and the author attribute was Andrew.
Now with the book1 object or instance created, we can now call different methods of the Book class on the instance like so:
book1.getPages()
The above runs the getPages function in the Book class. Notice that this method although has a self attribute in the function, this was not called: book1.getPages() evaluation. The idea behind that is the instance of the class or the object of the class is represented by the self attribute. The concepts of OOP can be overwhelming at first but it is really interesting. You can reach out to me for more explanation on this subject and I will be honoured to help out.