1
我在我的Python書中發現了這個問題,但我在使用私有和公共屬性打印作者,標題和副本數方面遇到困難。使用Python的私有和公共屬性
下面是說明:
class Book(object):
def __init__(self,author,title,copies):
#The __init__ method must accept arguments for
#the author (private attribute)
#the title (public attribute) and
#the number of copies (private atrribute)
def display(self):
#The display method must display the information
#for the book, that is the author, title and number of copies
#available
def sell_book(self,sold):
#This method must extract from the number of copies available
#the number of copies sold.
#Test that the user doesn't sell more copies than there are
#available.
#Display a suitable message if it was the last copy sold
def main():
#create an instance of the Book class
myBook = Book(author="JB Wellington", title="The digital divide",
copies=40)
myBook.sell_book(sold=3)
myBook.display()
#main
main()
這裏是我的代碼:
class Book(object):
def __init__(self, author, title, copies):
self.__author = author
self.title = title
self.__copies = copies
def display(self):
print "author:", self.__author, "\n"
print "Tilte:", self.titile, "\n"
print "Number of copies:", self.__copies, "\n"
def sell_book(self, sold):
if self.__copies < 0
print"The last copie sold"
def main():
#create an instance of the Book class
myBook = Book(author="JB Wellington", titile="The digital divide", copies = 40)
myBook.sell_book(sold=3)
myBook.display()
#main
main()