在Python中从一个函数内部调用另一个函数

6

我开始学习Python,但我的代码有问题,希望有人能帮忙。我有两个函数,我想从一个函数中调用另一个函数。当我尝试调用函数时,它似乎被忽略了,所以我猜测问题出在我如何调用它上面。下面是我代码的片段。

# Define the raw message function
def raw(msg):
    s.send(msg+'\r\n')

    # This is the part where I try to call the output function, but it
    # does not seem to work.
    output('msg', '[==>] '+msg)

    return

# Define the output and error function
def output(type, msg):
    if ((type == 'msg') & (debug == 1)) | (type != msg):
        print('['+strftime("%H:%M:%S", gmtime())+'] ['+type.upper()+'] '+msg)
    if type.lower() == 'fatal':
        sys.exit()
    return

# I will still need to call the output() function from outside a
# function as well. When I specified a static method for output(),
# calling output() outside a function (like below) didn't seem to work.
output('notice', 'Script started')

raw("NICK :PythonBot")

编辑。实际上我调用的是raw()函数,它就在代码片段下面。 :)


3
你确定你要在那里使用 &| 吗? - Ignacio Vazquez-Abrams
1
你根本没有调用第一个函数... - Colin Dunklau
1
我在这里徒劳无功,但是raw和output是Python中已经使用的名称吗?尝试重新命名函数,看看是否会有任何变化。 - jmite
2
你应该发布一个预计可以直接运行的示例。这段代码片段显然是从某个较大的代码中剪切出来的。问题可能是由于未在此处呈现的代码引起的。尝试使用两个函数进行更简单的情况以确保其正常工作。 - pepr
1
我会小心使用 type 作为变量。它是一个内置函数。你可以覆盖它,但最好小心不要这样做。 - Brad Campbell
显示剩余13条评论
1个回答

13

尝试一个更简单的例子,比如这个:

def func2(msg):
    return 'result of func2("' + func1(msg) + '")'

def func1(msg):
    return 'result of func1("' + msg + '")'

print func1('test')
print func2('test')

它会打印:

result of func1("test")
result of func2("result of func1("test")")

注意函数定义的顺序是故意相反的。Python中函数定义的顺序并不重要。

你应该更明确地说明,哪些方面不适用于你。


感谢提供示例 :) - Dead-i
请检查您的原始代码。正如Ignacio所提到的,&|的含义与您期望的不同。Python使用andor表示布尔表达式。 - pepr

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接