2017-07-25 102 views
0

所以我是业余程序员,我想为一些基于文本的黑客游戏做些功能。其中,将会调用一个函数来让玩家找到战利品等等。所以我正在做一些“小规模测试”; 在我的测试过程中,我发现如果我有一个函数(它内部调用了一个不同的函数),那么一些文本被“打印”,第二个函数将被首先调用。延迟函数调用 - Python

#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 
================ 

有没有一种方法,使文本后调用该函数打印? 或者简单地延迟被调用的函数。 或者我正在做这个错误的方式? 谢谢你的时间。

+0

请注意'装饰'是'无',你最后的声明没有效果... –

回答

1

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

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

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

decorated = Decor(Hello) 
decorated 
0

这是通常的方法之一来装饰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() 

这样在你DecorHello功能的语句不叫,直到你请致电decorated()

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

Hello() # is now the decorated version. 

有一个primer on decorators on realpython.com,这可能有助于:

,你可以使用装饰也是这样。