我是 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>" + _name + "</name>" \
+ "<isbn>" + _isbn + "</isbn>" \
+ "<price>" + str(_price) + "</price>" \
+ "<picture>" + _picture + "</picture>" \
+ "<link>" + _link + "</link>"
return xmlString
最初,我实际上MakeXMLString
在类中有一个方法,如下所示:
def MakeXMLString(self):
self.xmlString = "<name>" + self.name + "</name>" \
+ "<isbn>" + self.isbn + "</isbn>" \
+ "<price>" + str(self.price) + "</price>" \
+ "<picture>" + self.picture + "</picture>" \
+ "<link>" + self.link + "</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 "<stdin>", line 1, in <module>
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
班级完全可以访问。