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(".....")
CodePudding user response:
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
or you can do:
class Rooms:
def bedroom():
print(".....")
def start():
print(".....")
answer = input(">")
if "1" == answer
Rooms.bedroom() #Fixed
CodePudding user response:
Answer
In your case, you needed to create an instance that represents the class itself, so that other functions can call each other and share variables and data. A name that's most commonly used is self.
Having to define bedroom() before start isn't really necessary.
class Rooms:
def start(self): # Call 'self' to enable use
print(".....") # of other variables and
answer = input(">") # functions
if "1" == answer:
self.bedroom()
def bedroom(self):
print(".....")
More help
Go over this guide in OOP to understand the basics and examples on using OOP in Python
CodePudding user response:
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
