'NameError: name not defined when calling function inside of a class
I am new to python and writing a simple text based adventure game, I am receiving an error that says "NameError: name 'bedroom' is not defined". I initially had a bunch of function definitions in which case everything was working but decided to group them into classes which is when the error began.
class Rooms:
def start():
print(".....")
answer = input(">")
if "1" == answer
bedroom() #this is the line the error is coming from
def bedroom():
print(".....")
Solution 1:[1]
you can do: or add an self as parameters of functions, or you can call doing CLASS_NAME.FUNC_NAME()
so you should do:
class Rooms:
def bedroom(self):use self as a parameter
print(".....")
def start(self): #use self as a parameter
print(".....")
answer = input(">")
if "1" == answer:
self.bedroom() #nothe the use of self
And, NEVER do this:
class Rooms:
def bedroom():
print(".....")
def start():
print(".....")
answer = input(">")
if "1" == answer
Rooms.bedroom() #Fixed
Solution 2:[2]
To invoke a method from within the same class you need to pass the parameter self which is used to reference the current class to the method and invoke bedroom() in this case it is done like so self.bedroom() instead of invoking it like this bedroom():
class Rooms:
def bedroom(self):use self as a parameter
print(".....")
def start(self): #use self as a parameter
print(".....")
answer = input(">")
if "1" == answer:
self.bedroom() #note the use of self
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 |
