[Tutor] trouble displaying instance attributes and methods

Danny Yoo dyoo@hkn.eecs.berkeley.edu
Fri, 22 Jun 2001 01:18:06 -0700 (PDT)


On Fri, 22 Jun 2001, Learn Python wrote:

> 
> hi all,
> 
> This is what i have,
> 
> class test:
>    def __init__(self):
>      self.data = 100
>    def func(self):
>      pass
> 
> if __name__ == '__main__':
>    t = test()
>    dir(t) ==> i want this to list data and func
> 
> But it does'nt list func :-(. What methods s'd i provide in addition so that 

One small thing you forgot: you need to print the result of the
dir(); otherwise, you won't see anything.


Fixing that bug will still show some unusual behavior though:

###
>>> class test:
...     def __init__(self):
...         self.data = 100
...     def func(self): pass
... 
>>> t = test()
>>> dir(t)
['data']
###

As you might notice, t's dir() doesn't list func() out.  The reason is
because the methods stick around in the class, not the method, to avoid
duplicating the function over and over for each instance.  If we try
calling a method of an instance, and if it's not in the dir() of the
instance, Python will automagically look into the class itself for the
definition.

Let's use dir() on the class:

###
>>> dir(test)
['__doc__', '__init__', '__module__', 'func']
###


Hope this helps!