`final` keyword equivalent for variables in Python?

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

    Having a variable in Java be final basically means that once you assign to a variable, you may not reassign that variable to point to another object. It actually doesn't mean that the object can't be modified. For example, the following Java code works perfectly well:

    public final List messages = new LinkedList();
    
    public void addMessage()
    {
        messages.add("Hello World!");  // this mutates the messages list
    }
    

    but the following wouldn't even compile:

    public final List messages = new LinkedList();
    
    public void changeMessages()
    {
        messages = new ArrayList();  // can't change a final variable
    }
    

    So your question is about whether final exists in Python. It does not.

    However, Python does have immutable data structures. For example, while you can mutate a list, you can't mutate a tuple. You can mutate a set but not a frozenset, etc.

    My advice would be to just not worry about enforcing non-mutation at the language level and simply concentrate on making sure that you don't write any code which mutates these objects after they're assigned.

提交回复
热议问题