All data types in Python are “reference type“
Posted smstong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了All data types in Python are “reference type“相关的知识,希望对你有一定的参考价值。
LinuxExam.net: All data types in Python are "reference type"https://www.linuxexam.net/2022/11/all-data-types-in-python-are-reference.html
1 Value VS Reference in Java/C#
Programmers familiar with Java/C# should know that those two languages have two categories of data types, primitive (value) type and reference type.
The key difference between value type and reference type is that value typed data is directly a value while reference typed data is a reference (pointer) to the real data.
For value typed data like int, double Java/C# would just allocate memory space for its value.
For reference typed data like String, Java/C# would instead allocated memory space only for a pointer. The value of the pointer is the memory address where the actual value is allocated by "new" keyword to create an object.
Both Java and C# provide syntax sugar for creating String objects, so no explicitly "new" keyword is needed normally.
For value typed data, they're pure data; for reference typed data, the actual data usually has more information included, mostly pointers to methods to operate on the data.
To make it more clear, let compare the "int" and "Integer" in Java.
One thing about C# specially is "struct" is value-typed.
2 All data are reference typed in Python
In Python, data types become much simpler. "Everything in Python is an object!"
And any object is reference typed. So all data in Python is reference typed.
As all data are reference typed, any value is an object and has methods.
Please be noted that "100.__str__()" is not valid in Python due to conflicting with a float number syntax like "100.12". The wordaround is enclsing it with parentheses.
3 Thoughts
The main reason why Java/C# differentiate Value and Reference is PERFORMANCE. Value typed data are more efficient to operate and local variables only reside on stack, so no memory management load at all.
Python is a "PURE OBJECT ORIENTED" language where every single thing is a reference typed object. For example, Even if you just want a number 1, Python still needs to create a object for it. Creating and garbage collecting objects are not free for sure. In order to improve performance, Python makes many types like numbers and string "immutable". One advantage of "immutable" types is immutable objects can be shared safely.
For example,
n1 = 1
n2 = 1
Instead of creating two individual int objects, Python maybe just create one and let both n1 and n2 reference to this single object.
But be aware that "sharing immutable objects" is totally implementation's choice, and not a Python specification. Python users should NOT assume its exsitance.
以上是关于All data types in Python are “reference type“的主要内容,如果未能解决你的问题,请参考以下文章
Design a key value data structure support Get/Fetch/Delete/RandomDelete all in O