Pass parameters in pythonic form

1

The database driver I'm using, returns the data of a record in the form of tuple example ('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 being able to pass a tuple as a parameter to a function 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 like that when I started studying in python.

    
asked by anonymous 06.02.2016 / 18:24

2 answers

1

I'm not sure I understand correctly, but here's 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 running:

Nome: Joao
Idade: 32
Flag: False

More examples at: Learn Python

    
06.02.2016 / 19:27
0

Matheus, like @Gomiero said in the previous answer, 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)
    
23.03.2016 / 00:40