`final` keyword equivalent for variables in Python?

后端 未结 11 2299
忘了有多久
忘了有多久 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:33

    There is no final equivalent in Python. 

    But, to create read-only fields of class instances, you can use the property function.

    Edit: perhaps you want something like this:

    class WriteOnceReadWhenever:
        def __setattr__(self, attr, value):
            if hasattr(self, attr):
                raise Exception("Attempting to alter read-only value")
    
            self.__dict__[attr] = value
    

提交回复
热议问题