延迟函数调用 - Python

Delaying function calling - Python

所以我是业余程序员,我想为一个基于文本的小型黑客游戏做一些函数。在其中,将调用一个函数以允许玩家找到战利品等。所以我在做一些 'small-scale testing'; 在我的测试过程中,我发现如果我有一个函数(在它内部调用了一个不同的函数),那么一些文本是 'printed',第二个函数将首先被调用。

#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()

这样,在调用 decorated().

之前,不会调用 DecorHello 函数中的语句

你也可以这样使用装饰器:

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

Hello()  # is now the decorated version.

有一个 primer on decorators on realpython.com 可能会有所帮助。