我想在我的代码中替换字符串文字,因为我想最大限度地降低拼写错误的风险,特别是在dict键集中:
a['typoh'] = 'this is bad'
有人告诉我,这可以通过槽来实现,但我不知道如果不耍点小把戏怎么办。我可以想到以下几种方法:
这是一个无法接受的答案:
class TwiceIsNotNice(object):
this_is_a_string = 'this_is_a_string'
... (five thousand string constants in)
this_has_a_hard_to_spot_typographical_error =
'this_has_a_had_to_spot_typographical_error'
... (five thousand more string constants)
一个清晰但恼人的方法是使用“Stringspace”类/对象,在该类/对象中通过传入的字符串列表设置属性。这解决了打字风险最小化的问题,非常容易阅读,但既没有IDE可跟踪性,也没有自动完成功能。没关系,但会让人抱怨(请不要在这里抱怨,我只是在展示如何做到这一点):
string_consts = Stringspace('a', 'b',...,'asdfasdfasdf')
print(string_consts.a)
... where:
class Stringspace(object):
def __init__(self, *strlist):
for s in strlist:
setattr(self, s, s)
另一种方法是使用sentinel对象定义类,在post阶段设置值。这没问题,是可跟踪的,表现为一个实际的类,允许别名等,但它需要一个恼人的额外调用在类的末尾:
same = object()
class StrList(object):
this_is_a_strval = same
this_is_another_strval = same
this_gets_aliased = "to something else"
# This would of course could become a function
for attr in dir(StrList):
if getattr(StrList, attr) is same:
setattr(StrList, attr, attr)
print(StrList.a)
如果这就是槽魔术的意义所在,那么我很失望,因为必须实际实例化一个对象:
class SlotEnum(object):
__slots__ = []
def __init__(self):
for k in self.__slots__:
setattr(self, k, k)
class Foo(SlotEnum):
__slots__ = ['a', 'b']
foo_enum_OBJECT = Foo()
print(foo_enum_OBJECT.a)
E.a.name
获取a
是哑的。你知道吗我发现一个解决方案at this external link使用一个自定义的元类,用于包含字符串成员变量的类:
第1步(共2步):自定义元类的定义如下:
第2步(共2步):定义字符串的类可以这样定义(使用伪值,例如空元组):
测试:
输出:
相关问题 更多 >
编程相关推荐