2

Disclaimer: I'm doing my first steps in python that's why the question may sound a little silly.

How to list all variables which are stored in self?

Roman
  • 64,384
  • 92
  • 238
  • 332

3 Answers3

5

You might want inspect.getmembers as it'll list members of objects even if those objects have __slots__ defined as those objects do not have a __dict__.

>>> import inspect
>>> class F:
...     def __init__(self):
...             self.x = 2
... 
>>> inspect.getmembers(F())
[('__doc__', None), ('__init__', <bound method F.__init__ of <__main__.F instance at 0xb7527fec>>), ('__module__', '__main__'), ('x', 2)]
>>> class F:
...     __slots__ = ('x')
...     def __init__(self):
...             self.x = 2
... 
>>> inspect.getmembers(F())
[('__doc__', None), ('__init__', <bound method F.__init__ of <__main__.F instance at 0xb72d3b0c>>), ('__module__', '__main__'), ('__slots__', 'x'), ('x', 2)]
Dan D.
  • 73,243
  • 15
  • 104
  • 123
3

Every python object has a special member called __dict__ which is a dictionary containing all the instance's member.

self.__dict__.keys() lists their names

self.__dict__['foo'] gives you access to the value of the member foo

BTW, basically, writing something like self.foo = 1 is equivalent (at the basic level of things) to writing self.__dict__['foo'] = 1 that works as well.

Not_a_Golfer
  • 47,012
  • 14
  • 126
  • 92
  • 2
    Be warned that this is an oversimplification. Objects can (and some do, for good reasons) overload attribute access, which makes `__dict__` either incomplete or entirely useless. More commonly, `property` is used to create "attributes" which are not in `__dict__` and silently call a function. There's also `__slots__`, which can remove `__dict__` completely. And I'm sure there are more exceptions. –  Mar 11 '12 at 12:52
  • @delnan true, but since he was asking about the very basic use case, this is a good approximation. – Not_a_Golfer Mar 11 '12 at 12:54
2

If you're a beginner, you're asking a simple question so here's a simple answer: You can see all contents of a class or object, not just the variables but also the methods and other content, with the command dir. It's great when you're poking around at the python prompt. Try

dir("hello")  # examine string object
dir(str)      # examine string class
import os     
dir(os)       # Examine module

And yes, from inside a class you can use it to examine self, since self is just a class object. You can use dir, type and help on the contents of a class to get more detail about them: dir(os.stdout)

alexis
  • 48,685
  • 16
  • 101
  • 161