`final` keyword equivalent for variables in Python?

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

    you can simulate something like that through the descriptor protocol, since it allows to define reading and setting a variable the way you wish.

    class Foo(object):
    
      @property
      def myvar(self):
         # return value here
    
      @myvar.setter
      def myvar(self, newvalue):
         # do nothing if some condition is met
    
    a = Foo()
    print a.myvar
    a.myvar = 5 # does nothing if you don't want to
    

提交回复
热议问题