如何从类中创建列表?

时间:2013-12-03 20:20:12

标签: python function class

假设我有一个名为Books的类,其中包含变量:author,title和book_id。然后我有另一个类名Patrons,它有变量:name,patron_id和borroweds.Borroweds应该是当前“签出”的书籍列表所以我必须将类书籍加入到Patron类中。但是我该怎么做呢?

这是我到目前为止所做的:

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)

2 个答案:

答案 0 :(得分:2)

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)

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

class Book:
    # 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:
    # 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)+","+str(self.borroweds)+")")
        return s
    def __repr__(self):
        return str(self)

答案 1 :(得分:1)

您是否注意到书籍__str__方法中的拼写错误?最后的括号需要在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

每次创建Patron对象时,都可以在class属性中添加一个:

p1 = Patron('Dave',[Book('Me','Something', '8675309')])
print p1.patron_id
Patron.patron_id+=1
p2 = Patron('Dave',[Book('You','Others', 'Number9')])
print p2.patron_id

您会注意到class属性已更改并设置了objects属性。您甚至可以在Patron中创建一个类属性,该属性是每个Patron对象的列表,如果您愿意,可以在__init__方法中添加每个属性。它会在课堂上跟踪它。

此外,我认为您需要","+list(self.borroweds)+")"","+str(self.borroweds)+")"