我是Python新手,正在开发一个类来存储关于书籍的有意义的数据片段。我已经开始如下:class BookDisplay:
def __init__(self, _name, _isbn, _price, _picture, _link):
self.name = _name
self.isbn = _isbn
self.price = _price
self.picture = _picture
self.link = _link
self.xmlString = MakeXMLString(_name, _isbn, _price, _picture, _link)
name = ""
isbn = ""
price = 0.0
picture = "" #a URL
link = ""
xmlString = ""
我以为这个__init__方法只能够调用MakeXMLString,我在同一个文件(bookdisplay.py)中定义了它,就在BookDisplay类的下面:def MakeXMLString(_name, _isbn, _price, _picture, _link): #python multi-line syntax
xmlString = "" + _name + "" \
+ "" + _isbn + "" \
+ "" + str(_price) + "" \
+ "" + _picture + "" \
+ "" + _link + ""
return xmlString
最初,我实际上将MakeXMLString作为类中的一个方法,如下所示:def MakeXMLString(self):
self.xmlString = "" + self.name + "" \
+ "" + self.isbn + "" \
+ "" + str(self.price) + "" \
+ "" + self.picture + "" \
+ "" + self.link + ""
在这种情况下,__init__包含此调用:self.xmlString = self.MakeXMLString()
在这两种情况下,当尝试从另一个文件实例化BookDisplay时:from bookdisplay import BookDisplay
...
...
thumbnails = []
...
thumbnails.append(BookDisplay(titleField, "-1", float(priceField), imgField, linkField))
…我收到以下全局名称错误(此回溯尤其针对不在类内的函数):Traceback (most recent call last):
File "", line 1, in
File "search.py", line 30, in ebaySearch
handleDocument(doc)
File "search.py", line 59, in handleDocument
handleItems(items, outputFile)
File "search.py", line 102, in handleItems
thumbnails.append(BookDisplay(titleField, "-1", float(priceField), imgField, linkField))
File "bookdisplay.py", line 15, in __init__
self.xmlString = MakeXMLString(_name, _isbn, _price, _picture, _link)
NameError: global name 'MakeXMLString' is not defined
我错过了什么?据我所知,MakeXMLString对类是完全可访问的。