如何在 Python 中将对象作为字典键传递(TestComplete 问题?)

How to pass an object as a dictionary key in Python(TestComplete issue?)

我知道字典键必须是字符串或不可变对象。但我不想将字符串作为键传递。原因是,在我使用字典的每个地方,我都必须输入准确的字符串,并留下如此多的硬编码和错误空间。

这只发生在 TestComplete (V12) 上。 我可以做这样的事情吗,

class test():
    testStr = 'test'
    testStr2 = 'test2'

class Coverage():
     Data ={test.testStr    : True,
            test.testStr2   : 'something with white space'}

如果这是个坏主意,为什么?

您可以为此目的使用 Enum。

from enum import Enum     # for enum34, or the stdlib version
# from aenum import Enum  # for the aenum version
Animal = Enum('Animal', 'ant bee cat dog')

Animal.ant  # returns <Animal.ant: 1>
Animal['ant']  # returns <Animal.ant: 1> (string lookup)
Animal.ant.name  # returns 'ant' (inverse lookup)

或等同于:

class Animal(Enum):
    ant = 1
    bee = 2
    cat = 3
    dog = 4

data = {
    Animal.ant: 'small',
    Animal.dog: 'big'
}

这似乎是 TestComplete 的 Python 解析器中的一个问题,SmartBear 有一个补丁。您可以contact them获取补丁。