Function 延迟函数调用-Python

Function 延迟函数调用-Python,function,python-3.6,Function,Python 3.6,所以我是一个业余程序员,我想为一个基于文本的黑客游戏做些功能上的事情。在其中,将调用一个函数来允许玩家找到战利品等等。所以我在做一些“小规模测试”; 在我的测试过程中,我发现如果我有一个函数(在其中调用了另一个函数),那么一些文本被“打印”,第二个函数将首先被调用 #Example using a sort of 'Decorator'. def Decor(func): print("================") print("Hey there") print

所以我是一个业余程序员,我想为一个基于文本的黑客游戏做些功能上的事情。在其中,将调用一个函数来允许玩家找到战利品等等。所以我在做一些“小规模测试”; 在我的测试过程中,我发现如果我有一个函数(在其中调用了另一个函数),那么一些文本被“打印”,第二个函数将首先被调用

#Example using a sort of 'Decorator'.
def Decor(func):
    print("================")
    print("Hey there")
    print("================")
    print("")
    func

def Hello():
    print("And HELLO WORLD!")

decorated = Decor(Hello())
decorated
但输出总是沿着以下路线:

And HELLO WORLD!
================
Hey there
================
有没有办法在打印文本后调用函数? 或者简单地延迟正在调用的函数。 还是我走错了方向?
谢谢您的时间。

这里的问题是您正在将
Hello()
的结果传递给
Decor
。这意味着将首先处理
Hello()
,然后将结果作为参数传递给
Decor
。你需要的是这样的东西

def Decor(func):
    print("================")
    print("Hey there")
    print("================")
    print("")
    func()

def Hello():
    print("And HELLO WORLD!")

decorated = Decor(Hello)
decorated

这是python中修饰函数的常用方法之一:

def Decor(func):
    def new_func():
        print("================")
        print("Hey there")
        print("================")
        print("")
        func()
    return new_func

def Hello():
    print("And HELLO WORLD!")

decorated = Decor(Hello)
decorated()
这样,在调用
Decor
Hello
函数之前,不会调用函数中的语句

您也可以通过以下方式使用装饰器:

@Decor
def Hello():
    print("And HELLO WORLD!")

Hello()  # is now the decorated version.

有一个可能会有所帮助。

请注意,
修饰的
,您的最后一句话没有任何效果。。。