在另一个函数python中访问函数返回值

2024-09-30 14:37:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的程序,有一个类StatFind。这个类有三个方法。ncount方法返回字典列表:“finallist”。我需要将列表中的每一个字典添加到mongodb数据库中。在

如何访问inserttomongo()方法中的finallist。在

代码当前给出一个名称错误:

s.inserttomongo(finallist)
#=> NameError: name 'finallist' is not defined

这是我的代码:

^{pr2}$

Tags: 方法代码name程序名称数据库列表字典
1条回答
网友
1楼 · 发布于 2024-09-30 14:37:00

请阅读the Python tutorial尤其是the section about classes。在

你会在网上找到很多很棒的oopython教程,比如herehere。在

获取函数的返回值

 return_value = my_function(my_argument)

例如,通过在命令行上运行python来使用解释器:

^{pr2}$

清除代码:

你的代码没有意义。在

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

相关问题 更多 >