`final` keyword equivalent for variables in Python

2019-03-09 10:59发布

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 restoration if anything fails); once this backup variable is assigned, it should not be modified -- a final-like feature in Python would be nice for this.

9条回答
一夜七次
2楼-- · 2019-03-09 11:52

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.

查看更多
再贱就再见
3楼-- · 2019-03-09 11:53

There is no such thing. In general, the Python attitude is "if you don't want this modified, just don't modify it". Clients of an API are unlikely to just poke around your undocumented internals anyway.

You could, I suppose, work around this by using tuples or namedtuples for the relevant bits of your model, which are inherently immutable. That still doesn't help with any part of your model that has to be mutable of course.

查看更多
叛逆
4楼-- · 2019-03-09 11:54

Python has no equivalent of "final". It doesn't have "public" and "protected" either, except by naming convention. It's not that "bondage and discipline".

查看更多
登录 后发表回答