1

I have the following class which produces an error:

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

For now it won't recognize MyClass. If i remove "MyClass" python won't recognize the functions. I know I could move the static methods from inside the class outside as module functions. Is it possible to keep them inside the class and use them like I am trying?

asked Oct 19, 2016 at 8:37
3
  • 1
    You should ask yourself why you want a class here at all. Since it only contains static methods and attributes, it doesn't seem to be necessary to make it a class. Python is not Java; in Python the module is perfectly fine as a unit of encapsulation. Commented Oct 19, 2016 at 8:41
  • By the time you're trying to refer to MyClass._make_basic_query, neither the class definition is finished nor the method is defined. Commented Oct 19, 2016 at 8:44
  • @DanielRoseman there are more private and public methods inside MyClass. They are just removed for simplicity. Commented Oct 19, 2016 at 8:46

1 Answer 1

1

Change the order so that the dictionary is specified after the methods have been defined. Also don't use MyClass when doing so.

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
 }
 }

This works because when in the body of the class declaration, you can reference methods without needing the class type. What you are referencing has to have already been declared though.

answered Oct 19, 2016 at 10:29
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.