Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
Colin Hicks Avatar asked Sep 18 '25 05:09

Colin Hicks


1 Answers

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)])
like image 153
kederrac Avatar answered Sep 20 '25 19:09

kederrac