0

When calling a method (let's call this function_a) in Python that creates an object but doesn't return that object, does the object actually get created once function_a finishes running? Or once function_a stops running, is the object no more? If it does exist, what would happen differently if you return that object instead of just create it within the function?

I'm making my first text-based game with OOP in Python and working through a few kinks -- appreciate the help in advance!

What I did: I tried to run the following function, which creates a player and a spirit based on a few attributes that are passed in. This method belongs to a class called Engine(), and I included the forestcombat code at the bottom.

class Engine(object):

    # initializing the player and the spirit by calling to forestcombat
    def initialize_characters(self, mode, player_name):
        """Sets up the player and spirit characters based on the initial input"""

        player_attributes, spirit_attributes = forestcombat.gamemode(mode)
        name = player_name.lower()

        print(player_attributes)
        print(spirit_attributes)

        player_1 = forestcombat.Player(name, player_attributes['health'], player_attributes['XP'], player_attributes['elixir'])
        forest_spirit = forestcombat.Spirit(spirit_attributes['health'], spirit_attributes['attack_power'])

I later call this method inside of another method, expecting to create a Player() object from forestcombat. The player and spirit attributes both print properly, making me think that they are being created as I'd expect.

class MushroomPatch(object):
    # grab user input and then assign the number of mushrooms to their player attribute
    
    def enter(self, player_name):

        gamemode = 'hard'
        test = Engine()
        
        test.initialize_characters(gamemode, player_name)
        # is the player_1 object actually being initialized here?

        print(player_1.name)

However, I'm getting the following when I try to print (player_1.name):

NameError: name 'player_1' is not defined

What would happen differently if I return player_1 at the end of initialize_characters ?

~

For reference, the forestcombat code is below, which I call upon in Engine()

class Player(object):

    def __init__(self, playerName, playerHealth, playerXP, playerElixir):
        self.name = playerName
        self.health = playerHealth
        self.XP = playerXP
        self.elixir = playerElixir
  • 1
    The problem is more about **scope**. The `player_1` object is only ever defined and scoped to be part of the `initialize_characters` function, so you cannot access it outside of that function. Unless you return it and assign it to a variable scoped within the `enter` function. Then you can now access it. – Gino Mempin Nov 05 '22 at 09:54

0 Answers0