Class variable reference itself?

class variables python
python class
python self
python class attributes
python class inheritance
python class method
class members java
python private variables

I am new to coding period (3-ish weeks) and have been building and rebuilding a RPG to help teach myself the principles that I have been learning. However, I seem to be stuck on one specific aspect of Python classes.

A class variable I have created for my worldLocation class reads as such where the NORTH, EAST, SOUTH, WEST all reference strings:

WHITEROOM = worldLocation('A Plain White Room',
                          '...\n\nWhere are you?\n\n'
                          'All around you is white...\n\n'
                          '...only white...',
                          [ROCK.GROUNDDESC],
                          [RAT.NAME],
                          {NORTH: 'A Plain White Room',
                           SOUTH: 'A Plain White Room',
                           EAST: 'A Plain White Room',
                           WEST: 'A Plain White Room'})

But I want it to instead read like this, where each of the instance variables references the class variable itself:

WHITEROOM = worldLocation('A Plain White Room',
                          '...\n\nWhere are you?\n\n'
                          'All around you is white...\n\n'
                          '...only white...',
                          [ROCK.GROUNDDESC],
                          [RAT.NAME],
                          {NORTH: WHITEROOM,
                           SOUTH: WHITEROOM,
                           EAST: WHITEROOM,
                           WEST: WHITEROOM})

However, every time I attempt to change it to the latter, I receive an undefined name WHITEROOM error. What am I doing wrong or missing?

The class code is as follows:

class worldLocation(object):
    def __init__(self, NAME, DESC, GROUND, ENEMIES, DIRECTIONS):
        self.NAME = NAME
        self.DESC = DESC
        self.GROUND = GROUND
        self.ENEMIES = ENEMIES
        self.DIRECTIONS = DIRECTIONS

The code you want to use is trying to reference the instance in a dictionary being passed as argument to __init__() before it exists. That's not feasible (and arguably really reasonable if you think about it).

However, you can workaround the issue by creating a special value that the class initializer __init__() method can check for and fix-up the data being passed.

Below is code illustrating what I mean. Note I've added some scaffolding at the beginning to make it runnable for testing purposes.

#### Some scaffolding for testing.
NORTH, SOUTH, EAST, WEST = 'NORTH SOUTH EAST WEST'.split()

class ROCK:
    GROUNDDESC = 'ground desc'

class RAT:
    NAME = 'Ricky'
####


class WorldLocation:
    THIS = object()  # A unique value.

    def __init__(self, NAME, DESC, GROUND, ENEMIES, DIRECTIONS):
        self.NAME = NAME
        self.DESC = DESC
        self.GROUND = GROUND
        self.ENEMIES = ENEMIES

        # Replace any values in DIRECTIONS dictionary argument that refer to the
        # instance being created (as designated by them being the class
        # attribute THIS).
        self.DIRECTIONS = {direction: self if value is self.THIS else value
                               for direction, value in DIRECTIONS.items()}


WHITEROOM = WorldLocation('A Plain White Room',
                          '...\n\nWhere are you?\n\n'
                          'All around you is white...\n\n'
                          '...only white...',
                          [ROCK.GROUNDDESC],
                          [RAT.NAME],
                          {NORTH: WorldLocation.THIS,
                           SOUTH: WorldLocation.THIS,
                           EAST: WorldLocation.THIS,
                           WEST: WorldLocation.THIS})

# Show that it works.
from pprint import pprint

print(f'id(WHITEROOM): 0x{id(WHITEROOM):08x}\n')
pprint(vars(WHITEROOM))

Sample output:

id(WHITEROOM): 0x010d0390

{'DESC': '...\n'
         '\n'
         'Where are you?\n'
         '\n'
         'All around you is white...\n'
         '\n'
         '...only white...',
 'DIRECTIONS': {'EAST': <__main__.WorldLocation object at 0x010D0390>,
                'NORTH': <__main__.WorldLocation object at 0x010D0390>,
                'SOUTH': <__main__.WorldLocation object at 0x010D0390>,
                'WEST': <__main__.WorldLocation object at 0x010D0390>},
 'ENEMIES': ['Ricky'],
 'GROUND': ['ground desc'],
 'NAME': 'A Plain White Room'}

Self-Reference, Self-Reference. A method can refer to the current object using the %This system variable. Due to subtyping, %This is an object of either the method's class or a  Instance methods can access class variables and class methods directly. Class methods can access class variables and class methods directly. Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to. Constants


The variable doesn't get a value until after the function returns, so you can't refer to it in the arguments to the function. You have to add those references after you assign the variable.

WHITEROOM = worldLocation('A Plain White Room', '...\n\nWhere are you?\n\nAll around you is white...\n\n...only white...', [ROCK.GROUNDDESC], [RAT.NAME], {})
WHITEROOM.DIRECTIONS = {NORTH: WHITEROOM, SOUTH: WHITEROOM, EAST: WHITEROOM, WEST: WHITEROOM}

Understanding Class Members (The Java™ Tutorials > Learning the , Class variables are referenced by the class name itself, as in. Bicycle. Note: You can also refer to static fields with an object reference like. myBike. The class contains reference to one of its own kind.The best analogy in real world would be of a treasure hunt. A Clue place has some data and a clue in it which leads to another clue place which again you know repeats. It is not saying that a clue place has another clue place in it, the kind of which you are seeming to infer.


You can accomplish what you want to accomplish, but you cannot reference a variable before it's declared.

So, for example, you cannot say A={'key':A} because until the dict is created, it cannot be used as a value for 'key'.

Try this:

WHITEROOM = worldLocation('A Plain White Room', '...\n\nWhere are you?\n\nAll around you is white...\n\n...only white...', [ROCK.GROUNDDESC], [RAT.NAME], {})
WHITEROOM.DIRECTIONS = {NORTH: WHITEROOM, SOUTH: WHITEROOM, EAST: WHITEROOM, WEST: WHITEROOM}

Why does this work? Well, the worldLocation constructor __init__ will create the worldLocation object and assign it to the variable WHITEROOM. Then we can access the WHITEROOM.DIRECTIONS variable with the dot operator and pass it a new dict that uses the WHITEROOM variable as a reference to the WHITEROOM object. It's not as elegant as you'd like, but I think this way you'll be able to do what you're trying to do.

9. Classes, Variables and Class-local References), and all member functions are class MyClass: """A simple example class""" i = 12345 def f(self):  You can store members by reference if they are guaranteed to exist elsewhere. Reference member variables are used when the object they refer to exists outside of the scope of the class in question, and the same one is guaranteed to exist for the duration of the lifetime of your class' objects. A reference to the original is passed in as a parameter to the constructor and the reference member is initialized in the constructor's initializer list.


Understanding self in Python - Quick Code, So when accessed a class variable from any instance, the value will be the same. Instance variables, on the other hand, are variables which all  When you have member variables exposed through ref or pointer it violates the encapsulation in principle. This idiom enables the consumer of the class to change the state of an object of A without it(A) having any knowledge or control of it.


Javanotes 8.1, Section 5.1 -- Objects, Instance Methods, and , Instead of holding an object itself, a variable holds the information necessary to find the object in memory. This information is called a reference or pointer to the  A reference return value allows a method to return a reference to a variable, rather than a value, back to a caller. The caller can then choose to treat the returned variable as if it were returned by value or by reference. The caller can create a new variable that is itself a reference to the returned value, called a ref local.


Class and Object Variables, Remember, that you must refer to the variables and methods of the same object using the self variable only. This is called an attribute reference. In this program,  A varname variable set outside the init does belong to the class, and may be read via self.varname producing the same value for all instances. However, when assigned a value via an instance reference (as in self.varname = X) a new self.varname will be created for that instance only, obscuring the class variable.