How to pass Keywords Arguments in python in a simpler way?

Asked

Viewed 70 times

2

I’m trying to create the class button and trying to get the arguments I can pass pro rect, only if some argument is None and I pass for example self.rect = pygame.Rect(x=x) and the x for None of Error, so I’m doing so:

if x: 
    self.rect_initial.x = x 

for each of the rect properties. You can play this in a loop for?

1 answer

1


Python is extremely flexible as the way of both passing and receiving function arguments.

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

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

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

In the case of a function that will pass only the parameters that are not None for a rect, it’s 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)
  • Wonderful. That’s why I like Python, there’s always something new to learn.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.