简体   繁体   English

列为Python类变量

[英]list as Python class variable

I want a class "Library" which has a class variable "books" which is a list of all the books in the library. 我想要一个类“ Library”,它具有一个类变量“ books”,该变量是库中所有书籍的列表。 So may class begins 所以可以上课

class Library:
    books = []

Now I want to add a book to my collection, but I can find no syntax to do so. 现在,我想将一本书添加到我的收藏中,但是找不到任何语法。 The model I have in my head is something like 我脑子里有个模型

def addBook(self, book):
    books.append(book)

which I would expect to call with something like from the main routine with something like 我希望可以从主例程中调用类似的东西

lib = Library()
b = Book(author, title)
lib.addBook(b)

However, I've not been able to find any way to do this. 但是,我无法找到任何方法来执行此操作。 I always get an error with the "append" where I try to add the book to the list. 我总是在尝试将书添加到列表中时出现“ append”错误。

You should declare books as an instance variable , not a class variable : 您应该将books声明为实例变量 ,而不是类变量

class Library:
    def __init__(self):
        self.books = []

    def addBook(self, book):
        self.books.append(book)

so you can create an instance of Library : 因此您可以创建Library实例

lib = Library()
b = Book(...)
lib.addBook(b)

Notes: 笔记:

  • For further information about self , you can read this post . 有关self更多信息,您可以阅读这篇文章
  • This assumes your Book class is implemented correctly. 这假定您的Book类已正确实现。

look at this example for the initialization and the setter: 在此示例中查看初始化和设置器:

class Library:
    def __init__(self):
        self.books = []
    def add(self, x):
        self.books.append(x)
class Library():
    def __init__(self):
        self.books = []
    def addBook(self, book):
        self.books.append(book)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM