How do I create a constant in Python?

后端 未结 30 3212
既然无缘
既然无缘 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

    There's no perfect way to do this. As I understand it most programmers will just capitalize the identifier, so PI = 3.142 can be readily understood to be a constant.

    On the otherhand, if you want something that actually acts like a constant, I'm not sure you'll find it. With anything you do there will always be some way of editing the "constant" so it won't really be a constant. Here's a very simple, dirty example:

    def define(name, value):
      if (name + str(id(name))) not in globals():
        globals()[name + str(id(name))] = value
    
    def constant(name):
      return globals()[name + str(id(name))]
    
    define("PI",3.142)
    
    print(constant("PI"))
    

    This looks like it will make a PHP-style constant.

    In reality all it takes for someone to change the value is this:

    globals()["PI"+str(id("PI"))] = 3.1415
    

    This is the same for all the other solutions you'll find on here - even the clever ones that make a class and redefine the set attribute method - there will always be a way around them. That's just how Python is.

    My recommendation is to just avoid all the hassle and just capitalize your identifiers. It wouldn't really be a proper constant but then again nothing would.

提交回复
热议问题