Object-oriented – what is the difference between Object and Value in Python

object-orientedpython

I have been trying to find this answer but I could not find the proper explanation

Some say that they are the same and others say otherwise

I know for a compound object, The object will consist of multiple values

But for simple objects like int or string can we say that they are identical and values are objects themselves?

Thank you

Best Answer

But for simple objects like int or string can we say that they are identical and values are objects themselves?

Not exactly but there is the concept of 'value object' which "represents a simple entity whose equality is not based on identity."

In Python when you use the == operator you are testing the identity of the object based on its value. When you use the is operator, you are testing object identity.

So conceptually, value objects are used as if they are values but technically they are still objects and it's good to keep that distinction in mind.

It's also possible that the implementation of value objects might be to reuse a single instance (when possible) of a value object. For example, in Java, string literals will be 'interned' to avoid creating multiple objects with the same string value. Similar optimizations occur with Integer instances. You should not depend on this in general, though and doing so may result in bugs.

Related Topic