Swix
Swix

Reputation: 35

Class Strings and print functions

I'm working on a text based game and I've done this so far:

class Map():
    room1 = ('sampletext')

print(Map(room1))

but then i get an error:

Traceback (most recent call last):
  File "C:/Users/Owner/Downloads/Text.py", line 3, in <module>
    print(Map(room1))
NameError: name 'room1' is not defined

and I don't understand why the string from the variable isn't being printed because i am calling the class, but it says that the variable isn't recognized as a variable in the code. I want feedback so I can finish up this game.

Upvotes: 1

Views: 44

Answers (2)

Prune
Prune

Reputation: 77857

The main problem is that you can't call a class. You can call a class method, or call a method on an instance of the class. The syntax

Map(room1)

attempts to create an instance (object) of Map, given the initialization argument room1, which should be a local variable.

With the class definition you've given, I think that the proper syntax is

print(Map.room1)

which references the value of the class attribute room1.

Upvotes: 0

U13-Forward
U13-Forward

Reputation: 71580

Try this:

class Map():
    room1 = ('sampletext')

print(Map.room1)

Output:

sampletext

Upvotes: 2

Related Questions