不受欢迎的python feedparser实例化遗物

时间:2010-01-17 05:25:41

标签: python feedparser

问题:如何终止实例化或确保我正在创建python universal feedparser的新实例?


的信息:

我正在制作一个程序,可以下载和编目大量的博客。除了一个不幸的bug之外,它运行良好。我的代码设置为获取博客网址列表并通过for循环运行它们。每次运行它都会选择一个URL并将其发送到一个单独的类,该类管理数据的下载,提取和保存到文件。

第一个网址工作正常。它下载整个博客并将其保存到文件中。但它下载的第二个博客也将包含第一个博客的所有数据,我完全不知道为什么。


代码段:

class BlogHarvester:
  def __init__(self,folder):
    f = open(folder,'r')
    stop = folder[len(folder)-1]
    while stop != '/':
        folder = folder[0:len(folder)-1]
        stop = folder[len(folder)-1]
    blogs = []
    for line in f:
        blogs.append(line)

    for herf in blogs:
        blog = BlogParser(herf)
        sPath = ""
        uid = newguid()##returns random hash.
        sPath = uid
        sPath = sPath + " - " + blog.posts[0].author[1:5] + ".blog"
        print sPath
        blog.storeAsFile(sPath)

class BlogParser:
  def __init__(self, blogherf='null', path='null', posts = []):
    self.blogherf = blogherf

    self.blog = feedparser.parse(blogherf)
    self.path = path
    self.posts = posts
    if blogherf != 'null':
        self.makeList()
    elif path != 'null':
        self.loadFromFile()

class BlogPeices:
  def __init__(self,title,author,post,date,publisher,rights,comments):
    self.author = author
    self.title = title
    self.post = post
    self.date = date
    self.publisher = publisher
    self.rights = rights
    self.comments = comments

我包含了一些片段,我认为这可能很有用。对不起,如果有任何令人困惑的文物。这个程序一直是一个痛苦的屁股。

2 个答案:

答案 0 :(得分:1)

问题是posts=[]。默认参数是在编译时计算的,而不是运行时,因此对象的生命周期内的对象的突变仍然存在。而是使用posts=None并测试:

if posts is None:
  self.posts = []

答案 1 :(得分:0)

正如Ignacio所说,任何发生在函数列表中的默认参数的突变都将保留在类的生命周期中。

来自http://docs.python.org/reference/compound_stmts.html#function-definitions

  

评估默认参数值   当函数定义是   执行。这意味着   表达式被评估一次,当时   定义了函数,那就是   相同的“预先计算”值用于   每次通话。这是特别的   了解默认情况时很重要   参数是一个可变对象,例如   列表或字典:如果是   函数修改对象(例如,通过   将项目附加到列表中)   默认值实际上已修改。   这通常不是什么   意。解决这个问题的方法是使用   没有作为默认值,并且是明确的   在它的身体测试它   功能

但是这会带来一些问题,你正在修改一个引用......所以你可能正在修改一个列表,该列表是不希望被修改的类的消费者:

例如:

class A:
  def foo(self, x = [] ):
    x.append(1)
    self.x = x

a = A()
a.foo()
print a.x
# prints: [1]
a.foo()
print a.x
# prints: [1,1]   # !!!! Consumer would expect this to be [1]
y = [1,2,3]
a.foo(y)
print a.x
# prints: [1, 2, 3, 1]
print y
# prints: [1, 2, 3, 1]  #  !!!! My list was modified

如果你要复制它:(见http://docs.python.org/library/copy.html

import copy
class A:
  def foo(self, x = [] ):
    x = copy.copy(x)
    x.append(1)
    self.x = x

a = A()
a.foo()
print a.x
# prints: [1]
a.foo()
print a.x
# prints: [1]   # !!! Much better =)
y = [1,2,3]
a.foo(y)
print a.x
# prints: [1, 2, 3, 1]
print y
# prints: [1, 2, 3]  #  !!!! My list is how I made it