How do I create a constant in Python?

后端 未结 30 2667
既然无缘
既然无缘 2020-11-22 09:07

Is there a way to declare a constant in Python? In Java we can create constant values in this manner:

public static          


        
30条回答
  •  醉酒成梦
    2020-11-22 09:30

    (This paragraph was meant to be a comment on those answers here and there, which mentioned namedtuple, but it is getting too long to be fit into a comment, so, here it goes.)

    The namedtuple approach mentioned above is definitely innovative. For the sake of completeness, though, at the end of the NamedTuple section of its official documentation, it reads:

    enumerated constants can be implemented with named tuples, but it is simpler and more efficient to use a simple class declaration:

    class Status:
        open, pending, closed = range(3)
    

    In other words, the official documentation kind of prefers to use a practical way, rather than actually implementing the read-only behavior. I guess it becomes yet another example of Zen of Python:

    Simple is better than complex.

    practicality beats purity.

提交回复
热议问题