Python函数为非空返回None

2024-09-30 04:33:50 发布

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

我编写了一个递归函数来查询Racktables数据库,跟踪对象之间的连接并将它们放入一个列表中。你知道吗

所有结果都被追加并扩展到我作为参数给出的列表中。 函数一直工作到return语句,但是列表在返回后给出None

我在要调试的函数中添加了一些print语句,列表中包含到目前为止所需的数据:

def plink(Objid, PortId, mylist):

    if len(mylist) < 2:                         #If this is the first run put he initial data in the list
        mylist.append(Objid)
        mylist.append(PortId)

    res = rt.GetLink(PortId)                    #check if port is connected 

    if res == (False, False):
        print 'exiting because not connected'   #debug
        return mylist                           #If not connected return list

    nextObj = rt.GetPortObjid(res[1])
    mylist.extend(res)
    mylist.append(nextObj)

    ispatch = rt.CheckObjType(nextObj, 50080)
    if ispatch[0][0] == 0:                      #If connected to a non-patch-unit, add data to list and exit
        print "exiting because next object {0} is not a patchunit, mylist is {1}".format(nextObj, mylist)  #debug
        return mylist

    patchPorts = rt.GetAllPorts(nextObj)

    if len(patchPorts) != 2:                    #check if the patchunit has the right number of ports
        mylist.append("Error, patch-unit must have exactly two ports")
        return mylist

    if patchPorts[0][2] == res[1]:              #check which port is unseen and call the function again
        print mylist
        plink(nextObj, patchPorts[1][2], mylist)
    else:
        print mylist
        plink(nextObj, patchPorts[0][2], mylist)

results = ['Initial data']
allconn = plink(159, 947, results)
print "The full connection is {0}".format(allconn)

(我跳过了这里的DB构造)

运行此代码将提供:

['Initial data', 159, 947, 'C150303-056', 4882, 1591L]
['Initial data', 159, 947, 'C150303-056', 4882, 1591L, 'C140917-056', 4689, 727L]
exiting because next object 1114 is not a patchunit, mylist is ['Initial data', 159, 947, 'C150303-056', 4882, 1591L, 'C140917-056', 4689, 727L, 'C140908-001', 3842, 1114L]
The full connection is None

调试打印显示的列表完全按照我的预期填充,但是当在函数外部打印时,也在预先分配给变量之后,我没有得到任何结果。你知道吗

我写这篇文章是为了在CentOS 6服务器上用Python2.6运行它。作为最后手段,我可以在virtualenv中运行它,但如果可能的话,我会避免使用它


Tags: the列表datareturnifisresprint
1条回答
网友
1楼 · 发布于 2024-09-30 04:33:50
if patchPorts[0][2] == res[1]:              #check which port is unseen and call the function again
    print mylist
    plink(nextObj, patchPorts[1][2], mylist)
else:
    print mylist
    plink(nextObj, patchPorts[0][2], mylist)

递归调用函数不会自动使内部调用将返回值传递给外部调用。您仍然需要显式地return。你知道吗

if patchPorts[0][2] == res[1]:              #check which port is unseen and call the function again
    print mylist
    return plink(nextObj, patchPorts[1][2], mylist)
else:
    print mylist
    return plink(nextObj, patchPorts[0][2], mylist)

相关问题 更多 >

    热门问题