假设我有一个名为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)
你有没有注意到书的方法有错别字?末尾的括号需要左移,在
self.book_id
之后。在您不需要类属性,因为它们是为每个“用户”提供“全局”目的的。因此,如果您想跟踪您的客户数量,您可以在每次创建一个时更新“全局”变量,如下所示:
每次创建用户对象时,都可以将其添加到类属性中:
^{pr2}$你会注意到属性被改变了。您甚至可以在
Patron
中创建一个class属性,该属性是每个Patron
对象的列表,如果需要,可以在{uinit}方法期间添加每个对象。它会在课堂上跟踪它。在另外,我认为你需要}
","+list(self.borroweds)+")"
成为{另外,跳过类属性,你不需要它们。在
^{pr2}$相关问题 更多 >
编程相关推荐