Reputation: 3
so I'm amateur programmer, and I wanted to do something with functions for a little text-based hacking game. In it, a function would be called to allow the player to find the loot and so forth. So I was doing some 'small-scale testing'; And during my testing, I found that if I had a function (which called a different function inside of it), then some text being 'printed', the second function would be called first.
#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
But the output is always something along the lines of:
And HELLO WORLD!
================
Hey there
================
Is there a way to make the function be called after the text is printed? Or simply delay the function being called. Or am I going about this the wrong way? Thanks for you time.
Upvotes: 0
Views: 84
Reputation: 46849
this is one of the usual approaches to decorate a function in 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()
this way the statements in your Decor
and Hello
functions are not called until you call decorated()
.
you could use the decorator also this way:
@Decor
def Hello():
print("And HELLO WORLD!")
Hello() # is now the decorated version.
there is a primer on decorators on realpython.com that might help.
Upvotes: 0
Reputation: 3802
The issue here is that you are passing the result of Hello()
to Decor
. This means that Hello()
will be processed first and then the result will be passed to Decor
as parameter. What you need is something like this
def Decor(func):
print("================")
print("Hey there")
print("================")
print("")
func()
def Hello():
print("And HELLO WORLD!")
decorated = Decor(Hello)
decorated
Upvotes: 1