类变量引用本身?

时间:2019-10-08 19:30:10

标签: python python-3.x class

我是编码阶段(3个星期)的新手,并且一直在构建和重建RPG,以帮助自己学习所学的原理。但是,我似乎只停留在Python类的一个特定方面。

我为worldLocation类创建的类变量按如下方式读取,其中NORTHEASTSOUTHWEST所有引用字符串:< / p>

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'})

但是我希望它改为这样读取,其中每个实例变量都引用类变量本身:

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})

但是,每次尝试将其更改为后者时,都会收到一个undefined name WHITEROOM错误。我在做错什么或想念什么?

类代码如下:

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

3 个答案:

答案 0 :(得分:0)

直到函数返回后,变量才会获得值,因此您不能在函数的参数中引用它。分配变量后,您必须添加这些引用。

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}

答案 1 :(得分:0)

您可以完成要完成的工作,但是不能在变量声明之前引用它。

例如,您不能说A={'key':A},因为在创建dict之前,它不能用作'key'的值。

尝试一下:

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}

为什么这样做?好吧,worldLocation构造函数__init__将创建worldLocation对象,并将其分配给变量WHITEROOM。然后,我们可以使用点运算符访问WHITEROOM.DIRECTIONS变量,并将其传递给新的dict,该变量使用WHITEROOM变量作为对{{1}的引用 }对象。 它没有您想要的那么优雅,但是我认为通过这种方式您将能够做您想做的事情。

答案 2 :(得分:0)

您要使用的代码正在尝试引用字典中的实例,该实例作为参数传递给__init__() 之前。那是不可行的(如果考虑的话,那可能真的很合理)。

但是,您可以通过创建一个特殊的值来解决该问题,该值可以由类初始化器__init__()方法检查并修复所传递的数据。

下面的代码说明了我的意思。 注意我在开始时添加了一些脚手架,以使其可运行以进行测试。

#### 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))

示例输出:

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'}