python - Why can't I create an instance of a class inside a function? -


this question has answer here:

here class in question:

class hero(object):     def __init__(self, name, hp, damage):         self.name = name         self.hp = hp         self.damage = damage 

here function in question:

def generatehero(heroname, herohp, herodamage):     myhero = hero(heroname, herohp, herodamage) 

the input:

generatehero("bob", 100, 10) 

it runs. when try "myhero.name" or access other attribute, get:

traceback (most recent call last):   file "<pyshell#25>", line 1, in <module>     myhero nameerror: name 'myhero' not defined 

when set variable myhero, created in scope of generatehero function. means visible within generatehero function, , can referenced there. referencing outside cause error experienced.

in order use hero you've generated, have generatehero return value generates, , assign myhero.

def generatehero(heroname, herohp, herodamage):     return hero(heroname, herohp, herodamage)  myhero = generatehero("bob", 100, 10)  print(myhero.name)  # out: bob 

now variable myhero in scope need to, , can referenced @ will.


Comments