gpt4 book ai didi

python - 类变量引用本身?

转载 作者:太空宇宙 更新时间:2023-11-03 20:18:38 25 4
gpt4 key购买 nike

我是编码期的新手(大约 3 周),并且一直在构建和重建 RPG,以帮助自学我一直在学习的原理。然而,我似乎陷入了 Python 类的一个特定方面。

我为 worldLocation 类创建的类变量读取为 NORTHEASTSOUTH >, WEST 所有引用字符串:

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

最佳答案

您要使用的代码正在尝试引用字典中的实例,该实例作为参数传递给 __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'}

关于python - 类变量引用本身?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58292893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com