Python Forum

Full Version: function 2 inside function 1 parameters
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I know there is an import for this but i forgot it. One of the parameters in my function requires a function. I'll try and say this more simply. Main executes function1. One of the parameters for function1 is another function, function2. My problem is the function is launching before straight out of the paramters. I can't put no parenthesis because function2 has parameters. TIA for your help.
It is very difficult to understand. Can you post some code explaining the issue? Functions are ordinary python objects, they can be used like any other type of parameters.
I have class shop. When making the __init__ I need to give it a function within one of the parameter player. If I give it the function though, the function executes from within the parameter of the class shop, rather than executing when the shop class executes it

def openCabin(p):
    gD.fill(black)
    health = getattr(p, 'damageTaken')
    healthSub = health - (health * 2)
    p.damageTake(healthSub)
    pygame.display.update()
    time.sleep(5)

Cabin = Building(260, 30, 200, 200, Buildings[1], openCabin(p))
The function executes one line 9 where it says "openCabin"
https://docs.python.org/3/library/functo...ls.partial Wrote:functools.partial(func, *args, **keywords)
  • Return a new partial object which when called will behave like func called with the positional arguments args and keyword arguments keywords. If more arguments are supplied to the call, they are appended to args. If additional keyword arguments are supplied, they extend and override keywords.

from functools import partial
 
 
Cabin = Building(260, 30, 200, 200, Buildings[1], partial(openCabin, p=p))
Another way give only in openCabin when instantiate the Cabin object.
class Bar:
    def __init__(self, open_cabin):
        self.open_cabin = open_cabin

def open_cabin(p):
    return p
Use:
>>> cabin = Bar(open_cabin)
>>> cabin.open_cabin
<function open_cabin at 0x0324B4B0>
>>> 
>>> # First now will executes the open_cabin function with a argument
>>> cabin.open_cabin(42)
42