How to enumerate an object's properties in Python?
for property, value in vars(theObject).items():
print(property, ":", value)
Be aware that in some rare cases there's a __slots__
property, such classes often have no __dict__
.
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__'}
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__'])
iterate over an instance object's attributes in Python
There's actually a very simple way to do this, using getattr
in place of eval
:
myClass = MyClass()
for a in dir(myClass):
if(a[:2] != "__"): #don't print double underscore methods
print a, getattr(myClass, a)
Output:
a 7
aAndB 9
b 2
This has the very big advantage of not needing to hard code in the name of your instance into the string, as is required using eval("myClass.{}".format(a))
Python iterating through object attributes
UPDATED
For python 3, you should use items()
instead of iteritems()
PYTHON 2
for attr, value in k.__dict__.iteritems():
print attr, value
PYTHON 3
for attr, value in k.__dict__.items():
print(attr, value)
This will print
'names', [a list with names]
'tweet', [a list with tweet]
How do i get my code to loop through all attributes of an object?
I guess the error occur here:
for i in test.list[self.value]: print (self.i)
should be:
for i in test.list[self.value]: print (i)
UPDATE
In this example you get both Numbers first and then the letters:
class test():
def __init__(self, *args) -> None:
my_list = []
value = 0
y = 0
value = 0
for x in args:
my_list.append(x)
print(y)
y += 1
print (my_list)
for i in my_list: print (i)
a = test("a", "b", "c", "d")
Related Topics
Check If a File Is Open in Python
How to Remove an Element in Lxml
Drawing Lines Between Two Plots in Matplotlib
How to Pick "X" Number of Unique Numbers from a List in Python
Capture Arbitrary Path in Flask Route
Word Count from a Txt File Program
How to Bind a List to a Parameter in a Custom Query in SQLalchemy
Removing Unicode \U2026 Like Characters in a String in Python2.7
Should I Call Close() After Urllib.Urlopen()
How to Set Folder Permissions in Windows
What Does the Term "Broadcasting" Mean in Pandas Documentation
Asyncio.Sleep() VS Time.Sleep()
Python String 'Join' Is Faster () Than '+', But What's Wrong Here
How to Remove the Left Part of a String