2

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
  • 328
  • 3
  • 12

3 Answers3

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,230
  • 10
  • 37
  • 68
  • 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
  • 131
  • 4
0

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
  • 15,932
  • 5
  • 29
  • 52