3

我是 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班级完全可以访问。

4

1 回答 1

2

当您定义MakeXMLString为方法时,它不会返回任何内容

self.xmlString = self.MakeXMLString()

将覆盖self.xmlString并使其指向方法本身。

以您现在定义的方式,MakeXMLString无法从其他文件访问,因此您还必须手动导入它:

from bookdisplay import BookDisplay, MakeXMLString

编辑:

重读时,您没有MakeXMLString从另一个文件调用,因此错误在 bookDisplay.py 中;确保

def MakeXMLString()

与类定义在同一缩进级别,否则将被解释为方法。

于 2013-04-30T22:55:31.600 回答