让我们采用以下代码,定义算术运算符对象(标记):
RegularExpressionValidator
我希望将运算符分组到某处,以便我可以迭代它们或检查成员资格。由于我稍后会添加很多其他内容,因此我只想将它们添加到一个地方,而不是两个(实现运营商但忘记将其添加到class Operator:
def __init__(self, precedence):
self.precedence = precedence
PLUS = Operator(0)
UPLUS = Operator(10)
MIN = Operator(0)
UMIN = Operator(10)
MULT = Operator(20)
operators = PLUS, UPLUS, MIN, UMIN, MULT
可能引起微妙的错误)。我尝试过像
operators
和类似,但这显然不是一个有效的Python语句。
我目前使用的解决方案是operators = (PLUS = Operator(0), MIN = Operator(0), ...)
定义:
dict
这样可以正常工作,但这意味着任何时候我想要使用单个运算符,我必须将其称为例如operators = dict(
PLUS=Operator(0),
MIN=Operator(0),
...
)
,而不是更短更清晰的operators['PLUS']
。我可以忍受哪些,但我想知道是否存在更好的解决方案。
答案 0 :(得分:2)
您可以使用Enum
:
from enum import Enum
class Operator:
def __init__(self, precedence):
self.precedence = precedence
def __str__(self):
return "Operator: prec={}".format(self.precedence)
class Operators(Enum):
PLUS = Operator(0)
UPLUS = Operator(10)
MIN = Operator(0)
UMIN = Operator(10)
MULT = Operator(20)
p = Operators.PLUS
print(p) # Operators.PLUS
print(p.name) # PLUS
print(p.value) # Operator: prec=0
答案 1 :(得分:1)
您可以执行以下操作:
class Operator:
def __init__(self, precedence):
self.precedence = precedence
Operator.PLUS = Operator(0)
Operator.UPLUS = Operator(10)
Operator.MIN = Operator(0)
Operator.UMIN = Operator(10)
Operator.MULT = Operator(20)
[o for o in dir(Operator) if not o.startswith('__')]
答案 2 :(得分:1)
为什么不让操作员将自己添加到您的组中?
class Operator:
all = []
def __init__(self, precedence):
self.precedence = precedence
self.all.append(self) # Modifies the class variable, as we haven't
# introduced an instance variable with that name.
PLUS = Operator(0)
UPLUS = Operator(10)
MIN = Operator(0)
UMIN = Operator(10)
MULT = Operator(20)
# Freeze the collection of Operators
Operator.all = tuple(Operator.all)
当然,这也适用于模块级变量中的集合:
operators = []
class Operator:
def __init__(self, precedence):
self.precedence = precedence
operators.append(self)
PLUS = Operator(0)
UPLUS = Operator(10)
MIN = Operator(0)
UMIN = Operator(10)
MULT = Operator(20)
# Freeze the collection of Operators
operators = tuple(operators)
如果必须将运算符添加到多个组中的一个组,则使表示该组的集合将运算符添加到用于初始化运算符的必需参数:
u_operators = []
non_u_operators = []
class Operator:
def __init__(self, precedence, group):
self.precedence = precedence
group.append(self)
PLUS = Operator(0, non_u_operators)
UPLUS = Operator(10, u_operators)
MIN = Operator(0, non_u_operators)
UMIN = Operator(10, u_operators)
MULT = Operator(20, non_u_operators)
# Freeze the collections of Operators
non_u_operators = tuple(non_u_operators)
u_operators = tuple(u_operators)