pythonpython-3.xoopconstantsclass-constants

Python class constant using class init method?


I've made a class which can be compared and sorted inside common data structures.

The thing is that I wanted to make two class constants for the maximum and minimum values that class can take. So I could call this value just importing MyClass and writing

obj = MyClass.MY_MAX_CONSTANT

The thing is that calling the constructor or init method to initialize these constants is not allowed.

In Java this would be declared as static and it would work, but I don't know how can I do a class / static constant in Python using the constructor / init method. Haven't found much googling but some general recipes for constants and suggestions for making properties.

I don't need a mechanism to avoid changing the constant value since I'm definitely not changing it.

My first try was:

class MyClass(object):
    MY_MAX_CONSTANT = MyClass(10,10)
    MY_MIN_CONSTANT = MyClass(0,0)

    def __init__(self, param1, param2): # Not the exact signature, but I think this works as an example 
        # We imagine some initialization work here
        self.x = param1
        self.y = param2


    # SORT FUNCTIONS
    def __cmp__(self, other):
        # Implementation already made here

    def __eq__(self, other):
        # Implementation already made here

    def __ne__(self, other):
        # Implementation already made here

    def __ge__(self, other):
        # Implementation already made here

    # And so on...

A second try, by using some functions for each constant:

class MyClass(object):
    def __init__(self, param1, param2): # Not the exact signature, but I think this works as an example 
        # We imagine some initialization work here
        self.x = param1
        self.y = param2
        MY_MAX_CONSTANT = None
        MY_MIN_CONSTANT = None

    @staticmethod
    def get_max(self):
        if not MyClass.MY_MAX_CONSTANT:
            MyClass.MY_MAX_CONSTANT = MyClass(10,10)
        return MyClass.MY_MAX_CONSTANT

    @staticmethod
    def get_min(self):
        if not MyClass.MY_MIN_CONSTANT:
            MyClass.MY_MIN_CONSTANT = MyClass(0,0)
        return MyClass.MY_MIN_CONSTANT    

    # SORT FUNCTIONS (I'm not writing them twice for spacing)

But I wanted to avoid strange function mechanisms only for making two constants.

I prefer the constant being in the class and not a module because it feels more natural to me, but I'm hearing any advice or suggestion. Can anyone point me a better pythonic solution?

Thanks


Solution

  • Add your constants after creating your class, you are allowed to add more class attributes:

    class MyClass:
        # ...
    
    MyClass.MY_MAX_CONSTANT = MyClass(10, 10)
    MyClass.MY_MIN_CONSTANT = MyClass(0, 0)
    

    Only when the class statement has completed running is the class object available, bound to the name MyClass. You can't create instances before this point.