I’m very comfortable with .NET objects and its framework for reference vs value types. How do python objects compare to .NET objects? Specifically, I’m wondering about equality obj1 == obj2, hash-ability (i.e. being able to put in a dict), and copying.
For instance, by default in .NET, all objects are reference types and their equality and hash code is determined by their address in memory. Additionally, assigning a variable to an existing object just makes it point to that address in memory, so there is no expensive copying occurring. It seems that this is the same for python, but I’m not entirely sure.
EDITS:
- Equality
ischecks for referential equality,==checks for value equality (but what does value equality mean for objects?)
I was able to find some useful info from the effbot written back in 2000:
Objects
All Python objects have this:
- a unique identity (an integer, returned by
id(x))- a type (returned by
type(x))- some content You cannot change the identity.
You cannot change the type.
Some objects allow you to change their content (without changing the
identity or the type, that is).Some objects don’t allow you to change their content (more below).
The type is represented by a type object, which knows more about
objects of this type (how many bytes of memory they usually occupy,
what methods they have, etc).
Equality
:
– An object with no
__cmp__or__eq__method definedwill raise an error if you try to compare itinherits its comparisons from the objectobject. This means that doinga > bis equivalent to doingid(a) > id(b).The
iskeyword is also used to see if two variables point to the same object. The==operator on the other hand, calls the__cmp__or__eq__method of the object it is comparing.Hashability
:
– An object is hashable if there is a
__hash__method defined for it. All of the basic data types (including strings and tuples) have hash functions defined for them. If there is no__hash__method defined for a class, that class will inherit it’s hash from the objectobject.Copying
:
–
copy,copy.deepcopy, and their respective in class methods__copy__and__deepcopy__. Usecopyto copy a single object,deepcopyto copy a heirarchy of objects.deepcopyEdits made at the suggestion of agf.