Return multiple values from class in python?

2793 views python

I have this little test code to see how classes work.

class Person:
    def __init__(self): = ("Mike")

    def myfunc(self):
      print("Hello my name is " +

p1 = Person()
hello = p1.myfunc()

What I want is for to be returned from the class so I can use it outside of the class. Is this possible? I want the value to be returned without the 'hello my name is' string, so when printing the value returned the output is 'Mike' not 'Hello my name is Mike'. For now, it's just one value as this is a test code. If it works perfectly here, I will put it on my real code to make sure it works.

answered question


You can access the name by - and similarly for any other Person object you make from the class

i already tried putting return in the myfunc(self) but what do I do after that?

Note that hello = ... assigns to None because you don't return anything in myfunc.

You don't need (and shouldn't write) a function that returns a person's name because you can just access it as

but I want to access the variable and print it out outside the class.

>>> print( <<<

so for me to return multiple values, i should just 'return variable1, variable2'? and then split it outside? i will try this now. Also would you mind to post this as an answer if it works?

How to return multiple values from a function has been answered here, so unless you explain how your question is different from that one, there's no need to post an answer.

problem: When I go to print, the class always comes up as invalid syntax... EDIT it works, only Mike came up!

Aran-Frey this question is intended for methods, not just functions. Therefore the code formatting may be different

2 Answers


(1)Return the value(s) from the function in the class as normal, using return variable.

(2)Then to print it outside the class, variable = (myClass().variable) and then print variable.

(3) If you didn't want to print it out, just use the variable as normal.

You have successfully managed to get values from the class and used it in the whole program, without the need for the global keyword!

EDIT it looks like you don't even need to return the values: (myClass().variable) will get the value straight from the class without even needing to return the values, as supported by this code:

class Person:
    def __init__(self):
        self.name1 = ("Mike")
        self.name2 = ("John")
        self.name3 = ("Jane")
        self.name4 = ("Doe")

name1, name2, name3, name4 = (Person().name1), (Person().name2), (Person().name3), (Person().name4)
print (name1, name2, name3, name4)

posted this

Have an answer?


Please login first before posting an answer.