`final` keyword equivalent for variables in Python?

后端 未结 11 2301
忘了有多久
忘了有多久 2021-01-30 20:17

I couldn\'t find documentation on an equivalent of Java\'s final in Python, is there such a thing?

I\'m creating a snapshot of an object (used for restorati

11条回答
  •  感动是毒
    2021-01-30 20:45

    Although this is an old question, I figured I would add yet another potential option: You can also use assert to verify a variable is set to what you originally intended it to be set to – a double checking if you will. Although this is not the same as final in Java, it can be used to create a similar effect:

    PI = 3.14
    radius = 3
    
    try:
        assert PI == 3.14
        print PI * radius**2
    except AssertionError:
        print "Yikes."
    

    As seen above, if PI were for some reason not set to 3.14, an AssertionError would be thrown, so a try/except block would probably be a wise addition. Regardless, it may come in handy depending on your situation.

提交回复
热议问题