'How to determine an object's value in Python

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?



Solution 1:[1]

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.)

Solution 2:[2]

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"

Solution 3:[3]

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)])

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Andrew
Solution 2
Solution 3