Colin Hicks
Colin Hicks

Reputation: 360

How to determine an object's value in Python

From the Documentation

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

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

Upvotes: 4

Views: 18333

Answers (3)

kederrac
kederrac

Reputation: 17322

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

Upvotes: 3

Aswin Murugesh
Aswin Murugesh

Reputation: 11070

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"

Upvotes: 0

Andrew
Andrew

Reputation: 151

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

Upvotes: 0

Related Questions