Python对对象的引用以节省额外的键入
如何使用别名/引用/指向具有很长名称的对象以节省Python中的额外键入 我希望类似于下面C++代码的工作:Python对对象的引用以节省额外的键入,python,pointers,reference,alias,Python,Pointers,Reference,Alias,如何使用别名/引用/指向具有很长名称的对象以节省Python中的额外键入 我希望类似于下面C++代码的工作: //example of a complex type, here it can be a class with an attribute //which is a map, mapping a string to two nested struct string * alias = &(very_long_variable_name.I_do_not["want"].to_c
//example of a complex type, here it can be a class with an attribute
//which is a map, mapping a string to two nested struct
string * alias = &(very_long_variable_name.I_do_not["want"].to_carry_with.me);
if(*alias == "hey" || *alias == "hi") {
*alias = "I saved a lot of typing!";
}
在Python中,当您
very_long_object_name_in_python = SomeClass()
short_name = very_long_object_name_in_python
print(id(very_long_object_name_in_python))
print(id(short_name))
您有相同的输出,这意味着它们引用相同的对象
从python教程网站的这张图片中可以看到,两个别名都引用了同一个类实例
更新:但这对字符串不适用,当您执行此赋值时,python将复制字符串并将引用保存在新变量中
当两个变量指向
bytearray
时,您可以操作该数组的元素:
s = "Hello World!"
b = bytearray(s.encode('utf-8'))
a = b
print(b)
b[0]=ord('C')
print(a)
print(b)
输出:
bytearray(b'Hello World!')
bytearray(b'Cello World!')
bytearray(b'Cello World!')
它不起作用,它是相同的输出,但如果您随后执行
short\u name=something
,则两个ID将更改,原始变量将保持不变,这仅适用于.append()或comparison之类的就地操作,如您的示例我指向的对象是字符串,如何更改其值?字符串在Python中是不可变的:-(您可以始终拥有一个保存字符串的中间对象。或者您可以使用bytearray@quamrana我不知道如何使用它们,我的代码会是什么样子?