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
?
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)]
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.
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)