2

I am writing a class which is basically a data structure to hold status codes and an associated dict with each status code. I want to call a method, providing a numeric status code and get a dictionary back.

class StatusCode(object):
    def __init__(self):
        self.codes  = {  0: { 'flag': "QEX_OK",      'message': "job successful"                                          },
                         1: { 'flag': "QEX_CMDLINE", 'message': "general cmd line syntax or semantic error"               }
             }
    @staticmethod
    def get_code(code):
        return self.codes[code]

How would I correctly achieve this?

Much thx.

2 Answers 2

4

Use @classmethod:

class StatusCode(object):
    codes  = {
            0: { 'flag': "QEX_OK",      'message': "job successful"                           },
            1: { 'flag': "QEX_CMDLINE", 'message': "general cmd line syntax or semantic error"},
            }

    @classmethod
    def get_code(cls, code):
        return cls.codes[code]
Sign up to request clarification or add additional context in comments.

3 Comments

What is "cls" in this example?
@BenH it's the class object, analogous to the instance object self in instance methods.
It's a reference to StatusCode class object, like self is reference to a created object instance
2

How about:

class StatusCode(object):
    codes  = {0: { 'flag': "QEX_OK",      'message': "job successful"                                          },
              1: { 'flag': "QEX_CMDLINE", 'message': "general cmd line syntax or semantic error"               }
             }

    @staticmethod
    def get_code(code):
        return StatusCode.codes[code]

print StatusCode.get_code(1)

1 Comment

Awesome this is what I needed.... I was messing around with init() and didn't need to. Much thx.

Your Answer

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.