Everything is an object in python - object class and type class

Steven D'Aprano steve at pearwood.info
Thu Jun 4 10:11:30 EDT 2015


On Thu, 4 Jun 2015 03:26 am, BartC asked about Value and Object:

> Are they in fact the same, or is there something else that can be done
> more reliably to show the difference?

In *Python*, they are the same. All values are implemented as objects.

But, speaking generically, Value and Object are as different as Value and
String, or Value and Integer, or Value and List. Objects are a specific
kind of value. Values may be:

- simple machine-specific types like byte, int16, single (float);
- simple compound types like array, record or struct, string;
- more complex compound types, such as objects (in the Object Oriented
Programming sense).

An object in this sense is basically a record or struct with added language
semantics. So in a language like Pascal, for example, there are a bunch of
machine-specific simple unstructured types:

    Real, Boolean, Char, Integer, ...

plus machine-specific compound types:

    Array, Record, String, ...

plus Objects (at least for recent enough Pascal compilers). In Java, for
example, you have "unboxed primitives" for various integer types,
and "boxed" objects.

In Python, all values are Objects:

- ints are low-level integers wrapped in an Object;
- floats are low-level C doubles wrapped in an Object;
- strings are arrays of characters wrapped in an Object;

etc.


> (However, I feel the internal representation of values shouldn't matter.
> Each type of value will have its own documented behaviour.)

Well, sometimes it might matter. My own feeling is that languages shouldn't
lie to you. If it offers both low-level primitives for efficiency and
high-level objects for convenience, it should make the difference explicit,
like Java does, or Pascal, or C++. Javascript tries to hide the difference,
which works really well until it doesn't, and then you get weird behaviour:


js> arr = [false, Boolean(false), new Boolean(false)];
false,false,false
js> for (i = 0; i < arr.length; ++i) {
  > print(arr[i]);
  > if (arr[i]) {print("Surprise!")} }
false
false
false
Surprise!


If you can come up with a sensible justification for why Boolean(false) is
falsey, but new Boolean(false) is truthy, you're a better man than me.

 

-- 
Steven




More information about the Python-list mailing list