如何从类中创建列表?

2024-09-29 06:28:18 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个名为Books的类,该类包含以下变量:author、title和book_id,然后我有另一个类名passors,它有变量:name、patron_id和借来的。借来的应该是一个当前“签出”的书籍列表,所以我必须将这些类图书合并到类用户中。但我该怎么做呢?在

到目前为止,我得到的是:

class Book:
    author= ""
    title = ""
    book_id= ""
    # the class constructor
    def __init__(self, author, title, book_id):
        self.title = title
        self.author = author
        self.book_id = book_id      
    def __str__(self):
        s = str("Books("+str(self.author)+", "+str(self.title)+", "+str(self.book_id+")"))
        return s
    def __repr__(self):
        return str(self)
class Patron:
    name= ""
    patron_id= ""
    borroweds= list()
    # the class constructor
    def __init__(self, name, patron_id, borroweds):
        self.name= name
        self.patron_id= patron_id
        self.borroweds= borroweds
    def __str__(self):
        s= str("Patron("+str(self.name)+","+str(self.patron_id)+","+list(self.borroweds)+")")
        return s
    def __repr__(self):
        return str(self)

Tags: thenameselfidreturntitledefbooks
2条回答

你有没有注意到书的方法有错别字?末尾的括号需要左移,在self.book_id之后。在

您不需要类属性,因为它们是为每个“用户”提供“全局”目的的。因此,如果您想跟踪您的客户数量,您可以在每次创建一个时更新“全局”变量,如下所示:

class Patron:
    patron_id= 0
    # the class constructor
    def __init__(self, name, borroweds):
        self.name= name
        self.patron_id=self.patron_id
        self.borroweds= borroweds

每次创建用户对象时,都可以将其添加到类属性中:

^{pr2}$

你会注意到属性被改变了。您甚至可以在Patron中创建一个class属性,该属性是每个Patron对象的列表,如果需要,可以在{uinit}方法期间添加每个对象。它会在课堂上跟踪它。在

另外,我认为你需要","+list(self.borroweds)+")"成为{}

borroweds = [Book('Author Authorsson', 'The book of books', 'ISBN76576575757')]
patron = Patron('thename', 'theid', borroweds)

>>> patron
Patron(thename,theid,[Books(Author Authorsson, The book of books, ISBN76576575757)])
>>> patron.borroweds[0]
Books(Author Authorsson, The book of books, ISBN76576575757)

另外,跳过类属性,你不需要它们。在

^{pr2}$

相关问题 更多 >