将函数内部的变量传递给函数外部的变量

时间:2012-03-07 19:10:58

标签: python function variables

我正在尝试设置一个新变量来引用函数内的变量。我的伪代码是这样的:

def myfunction():
   a bunch of stuff that results in
   myvariable = "Some Text"

在代码的下面我有这个:

for something in somethinglist:
   if something == iteminsomethinglist:
       myfunction()
       mynewvariable1 = myvariable
   elif something == iteminsomethinglist:
       myfunction()
       mynewvariable2 = myvariable
   else:
       mynewvariable3 = myvariable

我不断收到一条错误消息,上面写着:名称'myvariable'未定义

我想我认为如果我调用该函数,它会处理一些东西,我将结果传递给变量,然后将该变量引用到一个更独特的变量,它会存储它......但事实并非如此。

编辑:我附加了我的代码,因为我在第一篇文章中不够清楚。在我的函数中有一个变量我想在它之外引用(实际上有2个)我为没有说清楚而道歉。我虽然我原来的伪代码提出了这个问题。我也有一种感觉,这可能不是最好的方法。可能调用2个函数会更合适吗?我的代码如下:

def datetypedetector():

    rows = arcpy.SearchCursor(fc)

    dateList = []

    for row in rows:
        dateList.append(row.getValue("DATE_OBSERVATION").strftime('%m-%d-%Y'))

    del row, rows

    newList = sorted(list(set(dateList)))

    dates = [datetime.strptime(d, "%m-%d-%Y") for d in newList]

    date_ints = set([d.toordinal() for d in dates])

    if len(date_ints) == 1:
        DTYPE = "Single Date"
        #print "Single Date"
    elif max(date_ints) - min(date_ints) == len(date_ints) - 1:
        DTYPE = "Range of Dates"
        #print "Range of Dates"
    else:
        DTYPE = "Multiple Dates"
        #print "Multiple Dates"

    fcList = arcpy.ListFeatureClasses()

for fc in fcList:

    if fc == "SO_SOIL_P" or fc == "AS_ECOSITE_P":
        datetypedetector()
        ssDate = newList
        print fc + " = " + str(ssDate)
        ssDatetype = DTYPE
        print ssDatetype

    elif fc == "VE_WEED_P":
        datetypedetector()
        vwDate = newList
        print fc + " = " + str(vwDate)
        vwDatetype = DTYPE
        print vwDatetype

    else: 
        datetypedetector()
        vrDate = newList
        print fc + " = " + str(vrDate)
        vrDatetype = DTYPE
        print vrDatetype

2 个答案:

答案 0 :(得分:3)

如上所述,myvariable仅在myfunction的范围内定义 要使该变量中的值在函数外部可用,您可以从函数返回它:

def myfunction():
    myvariable = "Some Text"
    return myvariable

然后像这样使用它:

for something in somethinglist:
    if something == iteminsomethinglist:
        mynewvariable1 = myfunction()

编辑:添加到问题的新信息。

你的缩进似乎有些偏差,但这可能只是复制粘贴的麻烦 我想你想要做的是这样的事情:

  1. datetypedetector为参数调用fc函数。
  2. 从该功能返回DTYPE以供日后使用。
  3. 首先将函数签名更改为:

    def datetypedetector(fc):
                         ^^
    

    datetypedetector中的最终陈述:

        return DTYPE
    

    然后在调用它时将fc作为参数传递,最后一步是通过赋予DTYPE的返回值来从函数中返回datetypedetector

    for fc in fcList:
        if fc == "SO_SOIL_P" or fc == "AS_ECOSITE_P":
            DTYPE = datetypedetector(fc)
            ...
    

答案 1 :(得分:1)

组织代码的更好方法是执行以下操作:

def myfunction():
   return "Some Text"

for something in somethinglist:
   if something == iteminsomethinglist:
       mynewvariable1 = myfunction()
   elif something == iteminsomethinglist:
       mynewvariable2 = myfunction()
   else:
       mynewvariable3 = myfunction()
相关问题