`final` keyword equivalent for variables in Python?

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

    An assign-once variable is a design issue. You design your application in a way that the variable is set once and once only.

    However, if you want run-time checking of your design, you can do it with a wrapper around the object.

    class OnePingOnlyPleaseVassily(object):
        def __init__(self):
            self.value = None
        def set(self, value):
            if self.value is not None:
                raise Exception("Already set.")
            self.value = value
    
    someStateMemo = OnePingOnlyPleaseVassily()
    someStateMemo.set(aValue) # works
    someStateMemo.set(aValue) # fails
    

    That's clunky, but it will detect design problems at run time.

提交回复
热议问题