设置值为其名称的成员变量字符串

2024-04-18 18:36:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在我的代码中替换字符串文字,因为我想最大限度地降低拼写错误的风险,特别是在dict键集中:

a['typoh'] = 'this is bad'
  • 我不想把东西打两次(值有可能打错)
  • 我希望它能够被各种ide“跟踪”(即单击thru查看它的定义位置和转义完成)。你知道吗
  • 枚举不存在:“E.a.name”获取“a”是愚蠢的。你知道吗

有人告诉我,这可以通过槽来实现,但我不知道如果不耍点小把戏怎么办。我可以想到以下几种方法:

这是一个无法接受的答案:

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)

Tags: to对象方法inselfstringobjectis
2条回答
  • 枚举已出:E.a.name获取a是哑的。你知道吗
from enum import Enum, auto

class StrEnum(str, Enum):
    "base class for Enum members to be strings matching the member's name"

    def __repr__(self):
        return '<%s.%s>' % (self.__class__.__name__, self.name)

    def __str__(self):
        return self.name


class E(StrEnum):

    a = auto()
    this_is_a_string = auto()
    no_typo_here = auto()
>>> print(repr(E.a))
<E.a>

>>> print(E.a)
a

>>> print('the answer is: %s!' % E.a)
the answer is: a!

我发现一个解决方案at this external link使用一个自定义的元类,用于包含字符串成员变量的类:

第1步(共2步):自定义元类的定义如下:

class MetaForMyStrConstants(type):
    def __new__(metacls, cls, bases, classdict):
        object_attrs = set(dir(type(cls, (object,), {})))
        simple_enum_cls = super().__new__(metacls, cls, bases, classdict)
        simple_enum_cls._member_names_ = set(classdict.keys()) - object_attrs
        non_members = set()
        for attr in simple_enum_cls._member_names_:
            if attr.startswith('_') and attr.endswith('_'):
                non_members.add(attr)
            else:
                setattr(simple_enum_cls, attr, attr)

        simple_enum_cls._member_names_.difference_update(non_members)

        return simple_enum_cls

第2步(共2步):定义字符串的类可以这样定义(使用伪值,例如空元组):

class MyStrConstants(metaclass=MetaForMyStrConstants):
    ONE_LONG_STR = ()
    ANOTHER_LONG_STR = ()
    THE_REAL_LONGEST_STR = ()

测试:

print (MyStrConstants.ONE_LONG_STR)
print (MyStrConstants.ANOTHER_LONG_STR)
print (MyStrConstants.THE_REAL_LONGEST_STR)

输出:

ONE_LONG_STR
ANOTHER_LONG_STR
THE_REAL_LONGEST_STR

相关问题 更多 >