-3

クラスStatFindを使用したこのようなプログラムがあります。このクラスには 3 つのメソッドがあります。ncount メソッドは辞書のリストを返します: 'finallist'。これらの各辞書をリストから mongodb データベースに追加する必要があります。

inserttomongo() メソッド内で最終リストにアクセスするにはどうすればよいですか。

コードは現在 nameerror を与えます:

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)
4

1 に答える 1

3

特にPython チュートリアル、クラスに関するセクションをお読みください

herehereのように、オンラインで多数の優れた OO Python チュートリアルを見つけることができます。

関数の戻り値を取得する

 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

コードのクリーンアップ:

あなたのコードは意味がありません。

  1. とはnmaidcount().finallist?
  2. プログラムのどこで定義finallistしますか?
  3. なぜあなたは持っています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()
于 2013-06-25T16:15:18.110 に答える