Every Python object has certain attributes, namely a type, an id, a value and a reference counter.
My questions concerns the value.
By value, I mean exactly the same thing as that referred in this Python official documentation.
What are the values of the following objects?
- [1,2,3]
- (1,2,3)
- {“first”:1,”second”:2}
- ExampleClass
- ExampleClass()
I can understand the value of ‘simple’ builtin data types, however, I don’t see how we can know the values of these more complex objects.
Does just printing them to a terminal guarantee us that we’re seeing their values? (I would say that it may not be true, since we have special methods like __repr__
that can change what we see.)
Some of them are container objects. These container object values could be somewhat recursive, since they themselves have objects with their own values…
10
What are the values of the following objects?
The value of the object is the object. It is the stuff stored in the computer memory for the object.
The value of [1,2,3]
is the object [1,2,3]
.
how we can know the values of these more complex objects
Complex objects are the same as simple objects, all are the same objects. You might be interested in https://docs.python.org/3/c-api/arg.html#c.Py_BuildValue .
Does just printing them to a terminal guarantee us that we’re seeing their values?
No. You might see the representation of the value in a string. “Value” is the abstract thing stored in memory of the computer.
So you can’t override a __str__
of a list:
>>> a=[1,2,3]
>>> setattr(a,"__str__",lambda x: "Who am I?")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object attribute '__str__' is read-only
But for a custom object you can do anything:
>>> class ExampleClass:
... def __str__(x): return "Who am I?"
...
>>> print(ExampleClass())
Who am I?
These container object values could be somewhat recursive
Let’s clarify here. The list [1,2,3]
stores a reference to an to int
object 1
, to object 2
and object 3
. These are 4 different objects, with different values. The list [1,2,3]
is “recursive” in the sense it’s value contains the references to other objects.
1
The value of an object can be defined by equality with another object.
So according to this definition, the value of x
can be checked by evaluating the expression x == y
: If it is true, the value of x
is y
.
3