3

From the Documentation

Every object has an identity, a type and a value.

  • type(obj) returns the type of the object
  • id(obj) returns the id of the object

is there something that returns its value? What does the value of an object such as a user defined object represent?

Colin Hicks
  • 348
  • 1
  • 3
  • 13
  • 6
    `obj` itself is a value – sashaaero Aug 10 '19 at 14:36
  • `obj` is the value of the object you are talking about. – idkman Aug 10 '19 at 14:37
  • 2
    ok so when I say something such as print(obj) how is obj evaluated? – Colin Hicks Aug 10 '19 at 14:40
  • 1
    @ColinHicks it calls `str(obj)` if __str__() is defined or `repr(obj)` you can redefined that also with `__repr__` . – Albin Paul Aug 10 '19 at 14:43
  • @ColinHicks You don't print an object, what you print is some text that represents some information about the object. – Thierry Lathuille Aug 10 '19 at 14:46
  • `obj` itself will return the value. – ngShravil.py Aug 10 '19 at 14:48
  • It represents whatever the class was designed to represent – jonrsharpe Aug 10 '19 at 15:03
  • 3
    Everything in python is an object, and objects represent values in the same way that numerals represent numbers. It isn't really possible to "return" an object's value: all you can ever really do is display the value in the form of a *string-representation*. – ekhumoro Aug 10 '19 at 16:36
  • @ColinHicks the value of the object is not the object itself but rather what is contained in the object. The information stored inside the object – Chyanit Singh Jan 19 '20 at 19:14
  • 1
    @ekhumoro Thanks for that comment, it's the first time that the idea of "object value" started make sense to me. – sammy Oct 20 '20 at 18:43
  • @ekhumoro That's deep. Indeed, i think that in general it is always a matter of representing a newly defined concept in previously understood terms. If we understand 'strings' (or more fundamentally, bit arrays), then we can use them to represent new notions (like numbers), and later represent new concepts using numbers. – amka66 Oct 05 '22 at 12:29

3 Answers3

2

to really see your object values/attributes you should use the magic method __dict__.

Here is a simple example:

class My:
    def __init__(self, x):
        self.x = x
        self.pow2_x = x ** 2

a = My(10)
# print is not helpful as you can see 
print(a) 
# output: <__main__.My object at 0x7fa5c842db00>

print(a.__dict__.values())
# output: dict_values([10, 100])

or you can use:

print(a.__dict__.items())
# output: dict_items([('x', 10), ('pow2_x', 100)])
kederrac
  • 16,819
  • 6
  • 32
  • 55
0

For every Python class, there are special functions executed for different cases. __str__ of a class returns the value that will be used when called as print(obj) or str(obj).

Example:

class A:

    def __init__(self):
        self.a = 5

    def __str__(self):
        return "A: {0}".format(self.a)

obj = A()

print(obj)
# Will print "A: 5"
Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
  • an object may not have `__dict__` implemented, then what? – kederrac Aug 10 '19 at 14:54
  • wouldn't ```__dict__``` be inherited from object for all new-style classes? – Colin Hicks Aug 10 '19 at 15:10
  • also did you mean print(obj)? I tried the code snippet above and it didn't work – Colin Hicks Aug 10 '19 at 15:32
  • 2
    @AswinMurugesh It is wrong to say that `__str__` returns a *value*. What it actually does is return a *string-representation* of the object. Also, [`__dict__`](https://docs.python.org/3/library/stdtypes.html?highlight=__dict__#object.__dict__) has nothing whatsoever to do with [`dict`](https://docs.python.org/3/library/functions.html#func-dict). – ekhumoro Aug 10 '19 at 16:05
  • 1
    @ekhumoro when I try to include any`__dict__` attribute in a class seems thing to break. From what I’ve read, doing so is actually shadows an instances dictionary such that `trying obj.__dict__[‘attr’]` returned an error when it would otherwise return obj.attr. Is this correct? If so does that mean` __dict__ `should not be overridden as a class attribute? – Colin Hicks Aug 10 '19 at 18:35
  • 1
    @ColinHicks Yes. There is rarely any need to override `__dict__`, and it really has nothing to do with `dict`. I think they may have thinking of the [`dir`](https://docs.python.org/3/library/functions.html#dir) function, and the related [`__dir__`](https://docs.python.org/3/reference/datamodel.html#object.__dir__) method. – ekhumoro Aug 10 '19 at 18:48
  • 1
    @ColinHicks PS: the [vars](https://docs.python.org/3/library/functions.html#vars) function is more closely related to `__dict__`. – ekhumoro Aug 10 '19 at 18:53
0

Note that not all objects have a __dict__ attribute, and moreover, sometimes calling dict(a) where the object a can actually be interpreted as a dictionary will result in a sensible conversion of a to a native python dictionary. For example, with numpy arrays:

In [41]: a = np.array([[1, 2], [3, 4]])

In [42]: dict(a)
Out[42]: {1: 2, 3: 4}

But a does not have an attribute 1 whose value is 2. Instead, you can use hasattr and getattr to dynamically check for an object's attributes:

In [43]: hasattr(a, '__dict__')
Out[43]: False

In [44]: hasattr(a, 'sum')
Out[44]: True

In [45]: getattr(a, 'sum')
Out[45]: <function ndarray.sum>

So, a does not have __dict__ as an attribute, but it does have sum as an attribute, and a.sum is getattr(a, 'sum').

If you want to see all the attributes that a has, you can use dir:

In [47]: dir(a)[:5]
Out[47]: ['T', '__abs__', '__add__', '__and__', '__array__']

(I only showed the first 5 attributes since numpy arrays have lots.)

Andrew
  • 141
  • 4