Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Firstly, I'd emphasize that there is no such thing as <code>getClass().getFields()</code> in Python because an object can have a lot of fields that are not defined by class. Actually, to create a field in Python you just need to attribute a value to it. The fields are not <em>defined</em>, the are <em>created</em>:</p> <pre><code>&gt;&gt;&gt; class Foo(object): ... def __init__(self, value): ... # The __init__ method will create a field ... self.value = value ... &gt;&gt;&gt; foo = Foo(42) &gt;&gt;&gt; foo.value 42 &gt;&gt;&gt; # Accessing inexistent field ... foo.another_value Traceback (most recent call last): File "&lt;stdin&gt;", line 2, in &lt;module&gt; AttributeError: 'Foo' object has no attribute 'another_value' &gt;&gt;&gt; # Creating the field ... foo.another_value = 34 &gt;&gt;&gt; # Now I can use it ... foo.another_value 34 </code></pre> <p>So, you do not get the fields from a class. Instead, you get the fields from an object.</p> <p>Also, Python methods are only fields with some special values. Methods are merely instances of functions:</p> <pre><code>&gt;&gt;&gt; type(foo.__init__) </code></pre> <p></p> <p>It is important to note that to make it clear that there is no such method as <code>getClass().getMethods()</code> in Python and the "equivalent" of <code>getClass().getFields()</code> will return methods as well.</p> <p>Said that, how could you get the fields (or attributes, as they are frequently called in Python)? Of course you cannot get them from the class, since the objects store them. So you can get the <em>name</em> of the attributes of an object using the <code>dir()</code> function:</p> <pre><code>&gt;&gt;&gt; dir(foo) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'another_value', 'value'] </code></pre> <p>Once you got the attribute names, you can get each of them by using the <code>getattr()</code> function:</p> <pre><code>&gt;&gt;&gt; getattr(foo, 'value') 42 </code></pre> <p>To get all of them, you can use <a href="http://docs.python.org/tutorial/datastructures.html#list-comprehensions" rel="nofollow noreferrer">list comprehensions</a>:</p> <pre><code>&gt;&gt;&gt; [getattr(foo, attrname) for attrname in dir(foo)] [&lt;class '__main__.Foo'&gt;, &lt;method-wrapper '__delattr__' of Foo object at 0x2e36b0&gt;, {'another_value': 34, 'value': 42}, None, &lt;built-in method __format__ of Foo object at 0x2e36b0&gt;, &lt;method-wrapper '__getattribute__' of Foo object at 0x2e36b0&gt;, ... # Lots of stuff 34, 42] </code></pre> <p>At the end, you can find the values you set on some attributes.</p> <p>However, this list will contain methods, too. Remember they are attributes as well. In this case, we can make our list comprehension avoid callable attrbutes:</p> <pre><code>&gt;&gt;&gt; [attrname for attrname in dir(foo) if not callable(getattr(foo, attrname))] ['__dict__', '__doc__', '__module__', '__weakref__', 'another_value', 'value'] </code></pre> <p>Now, getting the actual values:</p> <pre><code>&gt;&gt;&gt; [getattr(foo, attrname) for attrname in dir(foo) ... if not callable(getattr(foo, attrname))] [{'another_value': 34, 'value': 42}, None, '__main__', None, 34, 42] </code></pre> <p>There still are some strange values there, such as <code>__dict__</code>, <code>__doc__</code> etc. They are some stuff you may want to ignore. If so, just put another criteria in your list comprehension:</p> <pre><code>&gt;&gt;&gt; [attrname for attrname in dir(foo) ... if not attrname.startswith('__') and ... not callable(getattr(foo, attrname))] ['another_value', 'value'] &gt;&gt;&gt; [getattr(foo, attrname) for attrname in dir(foo) ... if not attrname.startswith('__') and ... not callable(getattr(foo, attrname))] [34, 42] </code></pre> <p>There are other ways to do such things. For example, you can look a the <code>__dict__</code> and <code>__slots__</code> attributes of an object. However, I find the method I've presented to be clearer for beginners.</p> <p><strong>EDIT</strong> Two more points. First, the <a href="https://stackoverflow.com/questions/6139588/python-equivalent-of-javas-getclass-getfields/6139668#6139668">cls solution</a> is really good because it suggests you to look at the <a href="http://docs.python.org/library/inspect.html" rel="nofollow noreferrer"><code>inspect</code> module</a>.</p> <p>Also, you may want to get both the name and the value of an attribute. You can get it generating a list of tuples:</p> <pre><code>&gt;&gt;&gt; [(attrname, getattr(foo, attrname)) for attrname in dir(foo) ... if not attrname.startswith('__') and ... not callable(getattr(foo, attrname))] [('another_value', 34), ('value', 42)] </code></pre> <p>Fortunately, the <a href="http://docs.python.org/library/inspect.html#inspect.getmembers" rel="nofollow noreferrer">inspect.getmembers()</a> function suggested by cls does it better.</p> <pre><code>&gt;&gt;&gt; import inspect &gt;&gt;&gt; inspect.getmembers(foo) [('__class__', &lt;class '__main__.Foo'&gt;), # ... Lots of stuff ... ('another_value', 34), ('value', 42)] </code></pre> <p>To remove methods, just avoid callables:</p> <pre><code>&gt;&gt;&gt; inspect.getmembers(foo, lambda attr: not callable(attr)) [('__dict__', {'another_value': 34, 'value': 42}), ('__doc__', None), ('__module__', '__main__'), ('__weakref__', None), ('another_value', 34), ('value', 42)] </code></pre> <p>(Unfortunately, <code>inspect.ismethod()</code> didn't not work as I expected.)</p> <p>There are a lot of internal stuff yet and we cannot get then out directly as we did with the methods. Nothing that a list comprehension can solve again:</p> <pre><code>&gt;&gt;&gt; [(name, value) for name, value in inspect.getmembers(foo, lambda attr: not callable(attr)) ... if not name.startswith('__')] [('another_value', 34), ('value', 42)] </code></pre> <p>Python is a very dynamic language and this solution cannot work as well in some cases. Consider that it is possible to have an object which should storage a function to be used somewhere. A function is a callable object and the attribute will not be presented. However, it is <em>logically</em> an attribute, a data to be used. You should have this kind of stuff in mind. However, I bet you'll not get such problems too frequently.</p> <p>HTH</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload