When a function in a class returns a value, where is it returned to?

南楼画角 提交于 2019-12-24 10:04:00

问题


I've been learning about Classes and I got my code to work, but I'm just wondering where does the returned value go?

code:

from sys import exit
from random import randint

class Game(object):

    def __init__(self, start):
        self.pie = [ 'pie test']

        self.start = start

    def play(self):
        next_room_name = self.start
        while True:
            print "\n--------"
            room = getattr(self, next_room_name)
            next_room_name = room()

    def rooom(self):
        print "Test worked. good job"
        return "piez"

    def piez(self):
        print "pie room"
        exit(1)


a_game = Game("rooom")
a_game.play()

For example, in the code above I return "piez" in rooom() and it now takes me to the piez(self) function. However, where did the return value go to take me there?

Did it return "piez" outside the class and re-enter the class with the new value? Did it return the string "piez" to init(self, start) ? Did I just return the value to the previous function, play(self)?

Other than that, everything is working fine, but I just don't understand how I arrived at the piez(self) function, simply by returning "piez" in the previous function. In the past I jumped around functions just by typing in the name of it with (), but this way I'm returning a string and not sure how I'm jumping around.

Here's my observation:

1.) Instantiate class Game("Rooom") to a_game

2.) from a_game we call the play() function

3.) "Rooom" is sent to init and assigned to self.start

4.) play(self) starts and uses intialized function self.start and sets to next_room_name

5.) Loop starts. Next function is grabbed from next_room_name and assigned to room

6.) next_room_name is assigned to room() . Suddenly jump to rooom(self)

7.) We arrived at rooom(self) and return "piez"

8.) ?? Piez is returned somewhere... and we are now at piez(self)

Can someone help me fill in the gaps? It's driving me crazy. I hope I'm making sense... I've just been closely trying to understand this for an hour now, and even after breaking it down I seem to be misunderstanding something.


回答1:


You have slight confusion here:

5.) Loop starts. Next function is grabbed from next_room_name and assigned to room

6.) next_room_name is assigned to room() . Suddenly jump to rooom(self)

The return value of any statement is assigned to the left hand side of the equal sign, if the equal sign exists.

When you write

x = hello()

This means:

"Call hello and store any return value in x"

So it should be

"The return value of the function called by room() is stored in next_room_name"

Hopefully this clarifies it for you.



来源:https://stackoverflow.com/questions/11838075/when-a-function-in-a-class-returns-a-value-where-is-it-returned-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!