How to create a class instantiation using variables from a function return in Python 3?

Asked

Viewed 31 times

0

Hello, I wish I could instantiate the class Sala below using as arguments the return of the function choose_sala(): The ideal would be to call the class initialization when the function returns Sala, but I haven’t been successful so far.

Follow the simplified example:

Python 3

class Sala:
    def __init__(self, ano, turma):
        self.ano = ano
        self.turma = turma

        print(" Sala Escolhida foi... ")

    def say_hello:
        print("Hello!")

r1 = [] # desnecessário!

def choose_sala():
    r1 = ['8A']
    r1 = "".join(r1)
    print(r1)

    print(r1[0], " ", r1[1]) #para poder usar casa letra separadamente, não deu certo usando a lista normal.
    return r1

I wish I could use:

a = Sala(choose_sala())
a.say_hello() # teste da classe

1 answer

0


What you want to do is:

a = Sala(*choose_sala())

The * causes each returned element to be passed separately as a separate parameter for the class Sala.

See more about this in the official basic tutorial here.

  • Okay, thanks, it worked great, I knew it was something simple but not as simple as a *. Basic tutorial, here we go!

  • @Georgebueno Now that it’s worked out, can I mark my answer as accepted, to close the question? Just click on the green Checkmark next to the answer.

Browser other questions tagged

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