BenH
BenH

Reputation: 720

Refering to class variables without creating an instance in Python

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.

Upvotes: 2

Views: 1712

Answers (2)

Mikko Ohtamaa
Mikko Ohtamaa

Reputation: 83686

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]

Upvotes: 4

NPE
NPE

Reputation: 500893

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)

Upvotes: 2

Related Questions