问题描述
我在Python中找不到相当于Java的 final
的文档,有这样的事吗?
I couldn't find documentation on an equivalent of Java's final
in Python, is there such a thing?
我正在创建一个对象的快照(如果有任何失败则用于恢复);一旦分配了这个备份变量,它就不应该被修改 - Python中的类似最终功能对此很好。
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.
推荐答案
在Java中使用变量 final
基本上意味着一旦分配给变量,就不能将该变量重新分配给另一个对象。它实际上并不意味着无法修改对象。例如,以下Java代码运行良好:
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<String> messages = new LinkedList<String>();
public void addMessage()
{
messages.add("Hello World!"); // this mutates the messages list
}
但以下甚至不会编译:
but the following wouldn't even compile:
public final List<String> messages = new LinkedList<String>();
public void changeMessages()
{
messages = new ArrayList<String>(); // can't change a final variable
}
所以你的问题是关于 final 。它没有。
So your question is about whether final
exists in Python. It does not.
但是,Python确实有不可变的数据结构。例如,虽然您可以改变列表
,但您不能改变元组
。您可以改变设置
,但不能改变冻结
等。
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.
这篇关于`final`关键字相当于Python中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!