Skip to main content
 首页 » 编程设计

python之我可以为变量添加第二个名字吗

2025年05月04日9soundcode

我需要说服自己这是个坏主意。我想为同一个变量分配第二个名称,其内容可能会改变。

A='Bob' 
B=A #wrong function, I want to figure out something that works here. 
A='Alice' 
print A 
print B 

我希望 A 和 B 都打印“Alice”,但 B 打印“Bob”而 A 打印“Alice”。

我为什么要这样做?在我的代码中,我对一些数据使用同一个名称,这对处理有意义,但不同的名称对用户输入有意义。 argparse 似乎想根据命令行选项分配一个变量名。所以我想在输入数据时使用一个名称,但在处理数据时使用另一个名称。我宁愿避免将一个复制到另一个,但这是我的后备立场。

请您参考如下方法:

Python strings are immutable :

In Python the string object is immutable - each time a string is assigned to a variable a new object is created in memory to represent the new value.

维基百科文档 immutability and specific Python example .

获得所需行为的一种简单方法是将字符串包装在类中:

class MyClass: 
    SomeStr = "Any Val" 
 
A = MyClass 
A.SomeStr = "Bob" 
B=A 
B.SomeStr = "Alice" 
 
print(A.SomeStr) 
print(B.SomeStr) 

输出:

>>>  
Alice 
Alice 

现在您的 B=A 赋值创建了一个“浅”副本...这两个变量 A 和 B 指向同一个对象。