Get all object attributes in Python?
Use the built-in function dir()
.
Is there a built-in function to print all the current properties and values of an object?
You are really mixing together two different things.
Use dir()
, vars()
or the inspect
module to get what you are interested in (I use __builtins__
as an example; you can use any object instead).
>>> l = dir(__builtins__)
>>> d = __builtins__.__dict__
Print that dictionary however fancy you like:
>>> print l
['ArithmeticError', 'AssertionError', 'AttributeError',...
or
>>> from pprint import pprint
>>> pprint(l)
['ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
>>> pprint(d, indent=2)
{ 'ArithmeticError': <type 'exceptions.ArithmeticError'>,
'AssertionError': <type 'exceptions.AssertionError'>,
'AttributeError': <type 'exceptions.AttributeError'>,
...
'_': [ 'ArithmeticError',
'AssertionError',
'AttributeError',
'BaseException',
'DeprecationWarning',
...
Pretty printing is also available in the interactive debugger as a command:
(Pdb) pp vars()
{'__builtins__': {'ArithmeticError': <type 'exceptions.ArithmeticError'>,
'AssertionError': <type 'exceptions.AssertionError'>,
'AttributeError': <type 'exceptions.AttributeError'>,
'BaseException': <type 'exceptions.BaseException'>,
'BufferError': <type 'exceptions.BufferError'>,
...
'zip': <built-in function zip>},
'__file__': 'pass.py',
'__name__': '__main__'}
Print all properties of a Python Class
In this simple case you can use vars()
:
an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print(', '.join("%s: %s" % item for item in attrs.items()))
If you want to store Python objects on the disk you should look at shelve — Python object persistence.
Getting attributes of a class
Try the inspect module. getmembers
and the various tests should be helpful.
EDIT:
For example,
class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
return self.a
>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
('__dict__',
<dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
'a': '34',
'b': '12',
'myfunc': <function __main__.myfunc>}>),
('__doc__', None),
('__module__', '__main__'),
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
('a', '34'),
('b', '12')]
Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.
>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]
...and the more complicated of which can include special attribute name checks or even metaclasses ;)
Can I get all attributes that were defined in the __init__ method of a class?
You can do this by looking at the __dict__
attribute or using the vars
function like so:
class A:
def __init__(self):
self.a = "a"
self.b = "b"
print(A().__dict__) # prints {'a': 'a', 'b': 'b'}
print(vars(A())) # also prints {'a': 'a', 'b': 'b'}
Iterate over object attributes in python
Assuming you have a class such as
>>> class Cls(object):
... foo = 1
... bar = 'hello'
... def func(self):
... return 'call me'
...
>>> obj = Cls()
calling dir
on the object gives you back all the attributes of that object, including python special attributes. Although some object attributes are callable, such as methods.
>>> dir(obj)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bar', 'foo', 'func']
You can always filter out the special methods by using a list comprehension.
>>> [a for a in dir(obj) if not a.startswith('__')]
['bar', 'foo', 'func']
or if you prefer map/filters.
>>> filter(lambda a: not a.startswith('__'), dir(obj))
['bar', 'foo', 'func']
If you want to filter out the methods, you can use the builtin callable
as a check.
>>> [a for a in dir(obj) if not a.startswith('__') and not callable(getattr(obj, a))]
['bar', 'foo']
You could also inspect the difference between your class and its instance object using.
>>> set(dir(Cls)) - set(dir(object))
set(['__module__', 'bar', 'func', '__dict__', 'foo', '__weakref__'])
Related Topics
Embedding Ipython Qt Console in a Pyqt Application
How to Combine Python Asyncio with Threads
Generating Sublists Using Multiplication ( * ) Unexpected Behavior
How to Get a Single Result from a SQL Query in Python
How to Replace Django's Primary Key with a Different Integer That Is Unique for That Table
Python Re.Sub Back Reference Not Back Referencing
How to Fix "Importerror: Dll Load Failed" While Importing Win32Api
What Is an 'Endpoint' in Flask
Numpy: Fix Array with Rows of Different Lengths by Filling the Empty Elements with Zeros
Running a Tkinter Form in a Separate Thread
Matplotlib Semi-Log Plot: Minor Tick Marks Are Gone When Range Is Large
Download and Save PDF File with Python Requests Module
How to Redirect Stderr in Python
Python: My Function Returns "None" After It Does What I Want It To