Return multiple values from class in python?

2766 views python
6

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

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

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

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

What I want is for self.name 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

print(p1.name)?

You can access the name by p1.name - 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 p1.name.

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

>>> print(p1.name) <<<

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

10

(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?

JD

Please login first before posting an answer.