To output variables & properties for an object

Asked 2 years ago, Updated 2 years ago, 137 views

Does Python have a function like print_r of PHP? I have to see the status of the object when I debug it. Is there a similar function?

python debugging introspection pretty-print python-datamodel

2022-09-22 22:30

1 Answers

Write dir(), vars()

dir() is

If object is type or class object, the list stores the attribute names of the classes and the base classes.

If object does not support _dir__(), instead gather information from __dict__ attributes, etc.

If _getattr_() is defined separately in the object, the dir() returned may not be complete

The elements in the list are sorted alphabetically

vars() provides module, class, instance, and other __dict_ attributes of that have ___code> attribute.

class myClass(object):
    def __init__(self):
        pass
    def myFunc1(self):
        pass


from pprint import pprint
l = dir(myClass)

print "---print l---"
print l

print "\n\n---pprint(l)---"
pprint(l)

print "\n\n---pprint(l, indent=2)---"
pprint(l, indent=2)

Results)

---print l---
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'myFunc1']


---pprint(l)---
['__class__',
 '__delattr__',
 '__dict__',
 '__doc__',
 '__format__',
 '__getattribute__',
 '__hash__',
 '__init__',
 '__module__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__setattr__',
 '__sizeof__',
 '__str__',
'__subclasshook__',
 '__weakref__',
 'myFunc1']


---pprint(l, indent=2)---
[ '__class__',
  '__delattr__',
  '__dict__',
  '__doc__',
  '__format__',
  '__getattribute__',
  '__hash__',
  '__init__',
  '__module__',
  '__new__',
  '__reduce__',
  '__reduce_ex__',
  '__repr__',
  '__setattr__',
  '__sizeof__',
  '__str__',
  '__subclasshook__',
  '__weakref__',
  'myFunc1']


2022-09-22 22:30

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.