【问题标题】:How function is getting called without defining in python [closed]如何在没有在 python 中定义的情况下调用函数 [关闭]
【发布时间】:2013-10-09 05:41:48
【问题描述】:

这是程序:

import sys

def IndexSearchString():
    '''

    This function search a string in a password file through index and gives the result.

    :return: none
    :return type: none 
    :author: Neeraj    

    '''
    fieldindex = int(sys.argv[1])-1
    stringsrch = sys.argv[2]

    file_name = open("passwd", "r")

    for store_file in file_name:
        temp = store_file.split(":")
        search = temp[fieldindex]
        #print search 

        if stringsrch in search:
            print store_file
            #print sys.stdout.write(store_file)   
            return

#IndexSearchString() 

【问题讨论】:

  • 很抱歉,您必须更具体地说明您的问题。
  • 如果我删除最后一行 IndexSearchStrind() 并运行程序,它会被执行。
  • 我的意思是如果不定义函数,程序甚至会被执行。我是python的新手。
  • ,告诉我们“正常工作”是什么意思。如果我执行上面的代码,并注释最后一行,它将运行但什么也不做。在我看来,这工作正常。如果您有其他定义,则需要说明。
  • 然后发生了三件事之一。 1)您的缩进不正确(如建议但 DanielB 的回答)。 2)在添加评论(如@Bakuriu 建议)后,您实际上并没有保存它,或者 3)您在其他地方调用该函数。因为你是对的,如果你不调用函数,函数体就无法运行。

标签: python function python-2.6


【解决方案1】:

确保您的代码与问题中的代码完全相同(包括@Haidro 的编辑)

您在问题中粘贴的代码表明您的缩进是这样的:

def my_function():
    '''
    docstring
    '''
code_intended_for_my_function()

#my_function()

这将导致code_intended_for_my_function 被执行。这是“有效的”,因为docstring 使my_fuction 的定义有效(它什么也不做),然后立即执行code_intended_for_my_function。要对此进行测试,请在您拥有的代码中删除 docstring 并检查您是否收到 IndentationError,或者直接从问题中复制当前的代码,看看它是否按预期工作。

【讨论】:

  • 我没有使用文档字符串
  • @NeerajLad 上传您正在使用的文件,以便我们下载并查看。
  • 这里没有上传选项。它是一个带有“:”的文本文件
  • 谢谢。我得到了答案。定义函数后的缩进问题
  • @NeerajLad 如果它解决了您的问题,您应该接受这个答案(点击答案左侧的“勾号”形状)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多