1

I would like to retrieve all the attributes of a given instance. I know I could use __dict__, but it's not working in my case, because I'm declaring some attributes using the @property decorator.

class A():

    def __init__(self):
        self.a = ""
        self._b = ""

    @property
    def b(self):
        return self._b

    @b.setter
    def b(self, value):
        self._b = value

    def f(self):
         print "hello"

These are the results I get:

>>> A().__dict__
{'a': '', '_b': ''}
>>> dir(A())
['__doc__', '__init__', '__module__', '_b', 'a', 'b', 'f']

But the result I want is the following one:

>>> get_all_the_attributes(A())
{'a': '', '_b': '', 'b': ''}

Or:

>>> get_all_the_attributes(A())
['a', '_b', 'b']

Is there any way to do that ?

Community
  • 1
  • 1
julienc
  • 19,087
  • 17
  • 82
  • 82
  • @BhargavRao This would add the `f` method too – julienc Apr 27 '15 at 12:45
  • Oh yeah. i had forgotten bout that! – Bhargav Rao Apr 27 '15 at 12:45
  • Why do you want to see `b` listed in `instance.__dict__`? There is *no such attribute*, you have a property instead. – Martijn Pieters Apr 27 '15 at 12:45
  • 1
    Related: [list @property decorated methods in a python class](https://stackoverflow.com/q/27503965) – Martijn Pieters Apr 27 '15 at 12:47
  • @MartijnPieters Well, maybe the title is a bit missleading. I don't want `b` especially in `__dict__`, but I'd rather want a way to list all the attributes of my instance, including those for which I used the `@property` decorator. – julienc Apr 27 '15 at 12:48
  • @julienc: then see the other question, and append the keys of `__dict__` to that to get that list. – Martijn Pieters Apr 27 '15 at 12:49
  • @MartijnPieters Indeed, I think this is exactly what I need! Sorry for the duplicate post then, I did not find the original one when I looked for an answer. – julienc Apr 27 '15 at 12:51
  • Note that, unless you *particularly* need to access the "private" attribute (e.g. if `None` was an acceptable starting default but you wouldn't want a user to set it), you should assign to `b` rather than `_b` in `__init__`; this ensures that all access is managed correctly. – jonrsharpe Apr 27 '15 at 12:54
  • Not a problem, now your question can help future users find that post a little bit better. :-) – Martijn Pieters Apr 27 '15 at 12:54

0 Answers0