Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping over all member variables of a class in python

Tags:

python

People also ask

How do you access member variables in Python?

The variables that are defined inside the methods can be accessed within that method only by simply using the variable name. Example – var_name. If you want to use that variable outside the method or class, you have to declared that variable as a global. def access_method( self ):

How do you iterate over a class in Python?

Create an Iterator To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object. As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__() , which allows you to do some initializing when the object is being created.

What is __ dict __ in Python?

__dict__ in Python represents a dictionary or any mapping object that is used to store the attributes of the object. They are also known as mappingproxy objects.


dir(obj)

gives you all attributes of the object. You need to filter out the members from methods etc yourself:

class Example(object):
    bool143 = True
    bool2 = True
    blah = False
    foo = True
    foobar2000 = False

example = Example()
members = [attr for attr in dir(example) if not callable(getattr(example, attr)) and not attr.startswith("__")]
print members   

Will give you:

['blah', 'bool143', 'bool2', 'foo', 'foobar2000']

If you want only the variables (without functions) use:

vars(your_object)

@truppo: your answer is almost correct, but callable will always return false since you're just passing in a string. You need something like the following:

[attr for attr in dir(obj()) if not callable(getattr(obj(),attr)) and not attr.startswith("__")]

which will filter out functions


>>> a = Example()
>>> dir(a)
['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__',
'__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__',
'__sizeof__', '__str__', '__subclasshook__', 'bool143', 'bool2', 'blah',
'foo', 'foobar2000', 'as_list']

—as you see, that gives you all attributes, so you'll have to filter out a little bit. But basically, dir() is what you're looking for.


Similar to vars(), one can use the below code to list all class attributes. It is equivalent to vars(example).keys().

example.__dict__.keys()