超出范围的对象 Python
我最近在学习Python,遇到了一个关于对象创建的问题。我创建了一个叫做pdf的类,用来解析输入的pdf文件(这个部分是正常工作的)。我现在的问题是,分别创建的对象竟然共享内存空间,具体原因我还不太明白。
for root, dirnames, filenames in os.walk("../PDF_DB_100//"):
for filename in filenames:
if filename.endswith('.pdf'):
print filename
pdf("../PDF_DB_100/"+filename).get_info()
count+=1
if count == 10:
break
class pdf(object):
Uno = []
Dos = []
Tress = []
Quatro = []
def __init__(self,path):
operations, mostly appends onto the above variables
....
这段代码会在目录中查找.pdf文件,并为10个pdf文件创建一个pdf对象。但是,由于pdf对象没有被引用,难道在执行完get_info()这一行后,它就不应该再存在了吗?为什么这些不同的pdf对象会把数据添加到同一个列表中呢?
2 个回答
1
问题在于你把列表放在了对象里面,而不是放在构造函数里面。
你应该这样做。
class pdf(object):
def __init__(self):
self.Uno = []
4
在Python中,类的属性如果是在类的最上面定义的,那这些属性就是属于这个类本身的,而不是属于类的实例。
你可能想要的具体内容是
class pdf(object):
def __init__(self,path):
self.S_Linc = []
self.Short_Legal = []
self.Title_Number = []
self.Legal_Description = []
operations, mostly appends onto the above variables
....