How to pass keywords arguments in python in a simpler way?

2

I'm trying to create the button class and trying to get the arguments that I can pass pro rect, so if any argument is None and I pass for example self.rect = pygame.Rect(x=x) and x is None of the error, then I'm doing so:

if x: 
    self.rect_initial.x = x 

for each of the properties of rect. Can you play this in a for loop?

    
asked by anonymous 01.12.2017 / 15:57

1 answer

1

Python is extremely flexible in terms of both passing and receiving function arguments.

For what you want, the best thing seems to be to make the desired call (in the example case, the "rect") by passing the parameters in a dictionary, instead of typing the name of the parameters in the call. p>

To do this, simply prefix the dictionary with two ** .

That is, in Python, exemplo(a=1, b=2) is the same as writing: parametros = {"a":1, "b": 2}; exemplo(**parametros) .

In the case of a function that passes only parameters that are not None to a Rect, it is possible to do something like this:

def minha_func(x=None, y=None, centerx=None, centery=None, width=None, height=None):
    parametros = {}
    for variavel in "x y centerx centery width height".split():
        if locals()[variavel] is not None:
             parametros[variavel] = locals()[variavel]
    meu_rect  = pygame.Rect(**parametros)
    
01.12.2017 / 17:20