我有一个类似StatFind的程序。这个类有三种方法。 ncount方法返回一个字典列表:'finallist'。我需要将列表中的每个字典添加到mongodb数据库中。
如何访问inserttomongo()方法中的finallist。
该代码目前提供了一个名称错误:
s.inserttomongo(finallist)
#=> NameError: name 'finallist' is not defined
这是我的代码:
!/usr/bin/python
import pymongo,json
from datetime import date, timedelta
from collections import defaultdict
import os, sys,time,csv,glob
tsvs = glob.glob(sys.argv[1])
class StatFind:
def __init__(self,tsvs):
self.tsvs=tsvs
def ncount(self, tsvs):
if True:
finallist=[]
for path in tsvs:
....Someprocess....
returns a list
return finallist
def other(self):
samplestring= "something random"
print samplestring
def inserttomongo(self, finallist):
self.finallist=ncount().finallist
mongo=pymongo.Connection('localhost')
mongo_db=mongo['sample']
mongo_collection=mongo_db['users']
for dictvalue in self.finallist:
# for dictvalue in ncount(tsvs):
insert_id=mongo_collection.insert(dictvalue)
s=StatFind(tsvs)
s.ncount(tsvs)
s.other()
s.inserttomongo(finallist)
答案 0 :(得分:3)
请特别阅读the Python tutorial ,the section about classes。
你会在网上找到大量优秀的OO Python教程,例如here或here。
return_value = my_function(my_argument)
例如,通过在命令行上运行python来使用解释器:
➤ python
Python 2.7.2+ (default, Jul 20 2012, 22:15:08)
[GCC 4.6.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def square(x):
... return x*x
...
>>> four_squared = square(4)
>>> four_squared
16
您的代码没有意义。
nmaidcount().finallist
?finallist
?if True
?情况总是如此!这就是我的意思:
tsvs = glob.glob(sys.argv[1])
class StatFind:
# This is the instance initialiser.
def __init__(self,tsvs):
self.tsvs=tsvs
# here we define every instance of StatFind to have an attribute
# called 'finallist' which will be accessible by all methods
self.finallist = []
# We do our initialisation here, when we initialise our object,
# instead of in a separate method.
for path in self.tsvs:
finalist.append(do_something(path))
def inserttomongo(self):
# The 'self' parameter is automagically set up by python to
# refer to the instance when 'insertmongo()' is called on an instance
# for example, myInstance.insertmongo(), in which case
# self will be 'myInstance'
mongo=pymongo.Connection('localhost')
mongo_db=mongo['sample']
mongo_collection=mongo_db['users']
for dictvalue in self.finallist:
insert_id=mongo_collection.insert(dictvalue)
s=StatFind(tsvs) #This will call __init__() behind the scenes.
s.inserttomongo()