我有以下类会产生错误:
class MyClass(object):
QUERIES_AGGS = {
'query3': {
"query": MyClass._make_basic_query,
'aggregations': MyClass._make_query_three_aggregations,
'aggregation_transformations': MyClass._make_query_three_transformations
}
}
@staticmethod
def _make_basic_query():
#some code here
@staticmethod
def _make_query_three_aggregations():
#some code here
@staticmethod
def _make_query_three_transformations(aggs):
#some code here
目前它无法识别 MyClass。如果我删除“MyClass”,python 将无法识别这些函数。我知道我可以将静态方法从类内部移到外部作为模块函数。是否可以将它们保留在类中并像我一样使用它们?
最佳答案
更改顺序,以便在定义方法之后指定字典。这样做时也不要使用 MyClass
。
class MyClass(object):
@staticmethod
def _make_basic_query():
#some code here
pass
@staticmethod
def _make_query_three_aggregations():
#some code here
pass
@staticmethod
def _make_query_three_transformations(aggs):
#some code here
pass
QUERIES_AGGS = {
'query3': {
"query": _make_basic_query,
'aggregations': _make_query_three_aggregations,
'aggregation_transformations': _make_query_three_transformations
}
}
这是有效的,因为在类声明的主体中,您可以引用方法而无需类类型。不过,您引用的内容必须已经声明。
关于python - 在Python中的静态变量中分配类的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40126208/