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__'])
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]
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))
Looping through an object's (class instance) properties in python and printing them
Try not using private __dict__
,
you have python built-in function called vars()
def print_properties(self):
for prop, value in vars(self).items():
print(prop, ":", value) # or use format
Explantion of vars, from pythom offical docs:
Return the
__dict__
attribute for a module, class, instance, or any
other object with a__dict__
attribute.Objects such as modules and instances have an updateable
__dict__
attribute; however, other objects may have write restrictions on their
__dict__
attributes (for example, new-style classes use a dictproxy to prevent direct dictionary updates).Without an argument,
vars()
acts likelocals()
. Note, the locals
dictionary is only useful for reads since updates to the locals
dictionary are ignored.
How to iterate through attributes of an object defined by getters or @property?
You can use dir()
to get all the attributes, though that will include methods inherited from base classes, including all the dunder methods from object:
class MyClass:
def __init__(self):
self.foo = "bar"
@property
def myprop(self):
return "hello"
my_instance = MyClass()
for i in dir(my_instance):
print("object has attribute %s" % i)
prints:
object has attribute __class__
object has attribute __delattr__
object has attribute __dict__
object has attribute __dir__
object has attribute __doc__
object has attribute __eq__
object has attribute __format__
object has attribute __ge__
object has attribute __getattribute__
object has attribute __gt__
object has attribute __hash__
object has attribute __init__
object has attribute __init_subclass__
object has attribute __le__
object has attribute __lt__
object has attribute __module__
object has attribute __ne__
object has attribute __new__
object has attribute __reduce__
object has attribute __reduce_ex__
object has attribute __repr__
object has attribute __setattr__
object has attribute __sizeof__
object has attribute __str__
object has attribute __subclasshook__
object has attribute __weakref__
object has attribute foo
object has attribute myprop
You can exclude some with string operations:
for i in dir(my_instance):
if i.startswith("__"):
continue
print("object has attribute %s" % i)
prints:
object has attribute foo
object has attribute myprop
Iterate over unknown object attributes in Python
As @TheSoundDefense suggested you can use the vars()
built-in to list all the attributes of the object. The following answer extends the idea with an example of using it in your case
Implementation
class Foo(object):
def __init__(self, dictionary):
for k, v in dictionary.iteritems():
setattr(self, k, v)
def __iter__(self):
return iter(vars(self))
Demo
foo = Foo({'X':1, 'Y':2, 'Z':3})
for elem in foo:
print elem
Output
Y
X
Z
How to iterate over object attributes and check for duplicate in python?
The code is returning too early. You need to move else
part out of the loop to iterate all templates:
for template in templates:
if template.temp_name == temp_name:
data = {'status': 'exists'}
return JsonResponse(data)
data = {'status': 'exist_not'}
return JsonResponse(data)
BTW, you don't need to use loop. Use QuerySet.filter
to check whether there is matching template exist:
temp_name = request.POST.get('temp_name')
exists = EmailTemplate.objects.filter(temp_name=temp_name).exists()
data = {'status': 'exists' if exists else 'exist_not'}
return JsonResponse(data)
Iterate over an object's public attributes
You can prepare list of "public" attributes (as list or as generator) before:
>>> public_props = (name for name in dir(object) if not name.startswith('_'))
>>> for name in public_props:
print name
But please read a note about dir()
function in the documentation:
Note Because
dir()
is supplied primarily as a convenience for use at an interactive prompt, it tries to supply an interesting set of names more than it tries to supply a rigorously or consistently defined set of names, and its detailed behavior may change across releases. For example, metaclass attributes are not in the result list when the argument is a class.
You should also be aware, that any class can implement __dir__()
method that may return a list of names that do not necessarily correspond to the names of the attributes. In other words, dir(something)
does not guarantee that the result will return attributes of something
.
Related Topics
How to Redirect Stdout to Both File and Console with Scripting
How to Validate a Date String Format in Python
Ipython Reads Wrong Python Version
How to Stop a Looping Thread in Python
Python 3.7 Anaconda Environment - Import _Ssl Dll Load Fail Error
How to Return a Value from _Init_ in Python
How to Get Reproducible Results in Keras
MAC Osx Python Ssl.Sslerror: [Ssl: Certificate_Verify_Failed] Certificate Verify Failed (_Ssl.C:749)
Python - Use List as Function Parameters
Get Screenshot on Windows with Python
How Does Python Manage Int and Long
How to Overcome Typeerror: Unhashable Type: 'List'
How to Round a Floating Point Number Up to a Certain Decimal Place