使用Python的私有和公共属性

时间:2013-08-25 18:24:26

标签: python attributes

我在我的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()

1 个答案:

答案 0 :(得分:0)

问题是你在main()之前有不必要的{TAB}吗? 它应该在行的开头