Python 引用对象以节省额外输入
Python reference to object to save extra typing
如何 alias/reference/point 名称很长的对象以节省在 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_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-tutor 网站的这张图片中看到,两个别名都引用了 class.
的同一实例
UPDATE:但这不适用于字符串,当您执行此赋值时 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!')
如何 alias/reference/point 名称很长的对象以节省在 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_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-tutor 网站的这张图片中看到,两个别名都引用了 class.
的同一实例UPDATE:但这不适用于字符串,当您执行此赋值时 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!')