Python Forum
function 2 inside function 1 parameters - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: function 2 inside function 1 parameters (/thread-17694.html)



function 2 inside function 1 parameters - SheeppOSU - Apr-20-2019

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.


RE: function 2 inside function 1 parameters - Gribouillis - Apr-20-2019

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.


RE: function 2 inside function 1 parameters - SheeppOSU - Apr-20-2019

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"


RE: function 2 inside function 1 parameters - Yoriz - Apr-20-2019

https://docs.python.org/3/library/functools.html#functools.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))



RE: function 2 inside function 1 parameters - snippsat - Apr-20-2019

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