Pass pythonic form parameters

Asked

Viewed 1,150 times

1

The database driver I am using returns the data of a record in the form of an example tuple ('João', 32, False). I’m thinking of a pythonic way of passing this data to the constructor of a Person class, to create an object with the data contained in the tuple. I had seen somewhere something about it being possible to pass a tuple as a function parameter and it would recognize the values contained in the tuple as being the value of each parameter that the function expects. I’m not sure, but I think I saw something along those lines when I started my studies in python.

2 answers

1


I’m not sure I understand correctly, but follow an example:

def Pessoa(nome, idade, flag):
    print("Nome: {0}".format(nome))
    print("Idade: {0}".format(idade))
    print("Flag: {0}".format(flag))

In the function call, just put a * before the parameter:

parametro = ('Joao', 32, False)
Pessoa(*parametro)

When executing:

Nome: Joao
Idade: 32
Flag: False

More examples in: Learn Python

  • 1

    The answer is correct, but I don’t know if I’d call it pythonic. After all, "Explicit is better than implicit", and nothing more explicit in a passage of parameters than simply passing the parameters.

  • Buddy, wouldn’t it be better if you put the function so it only took one line? So it would be more efficient for your code and avoid using many . format()

  • @Viniciusmesel: Yes, it is another possibility, too. But the above example is only didactic and not aimed at performance :)

  • 1

    @Gomiero understand friend! I will add this answer also to be able to help you better.

0

Matheus, just as @Gomiero said in the previous reply, you can do the following:

def Pessoa(self, nome, idade, flag):
    return("Nome: {}\n\rIdade: {}\n\rFlag: {}".format(nome, idade, flag))

And to call the function:

parametros = (João, 35, True)
Pessoa(*parametros)

Browser other questions tagged

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