[Tutor] trouble displaying instance attributes and methods

Remco Gerlich scarblac@pino.selwerd.nl
Fri, 22 Jun 2001 10:19:02 +0200


On  0, Learn Python <learnpython@hotmail.com> wrote:
> 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 
> dir( ) can recognize func() which happens to be a instance method attribute? 
> I guess this s'd be possible bcos when i say
> l = [] and then dir(l), i get all the list attributes. I want the same kind 
> of behaviour for my class instance as well.

Python instances simply don't work that way - the class has methods, the
instance doesn't.

You do 'self.data = 100', so the instance has the 'data' attribute, but the
function func() is defined in the class.

When you do t.func(), Python first looks for 'func' in the instance, where
it doesn't find it. Then, because t is an instance, it looks in the
instance's class, where the method is found, and this is when the 'self'
argument is filled in. It's therefore quite important to the way Python works.

Lists are different because they're not instances of some class written
Python; they're a type, written in C. Types and classes are different.

You can make your own function that recursively shows the dir() of the
instance and its base classes, e.g.

def deep_dir(object):
   import types
   
   result = dir(object)
   if type(object) is types.InstanceType:
      result.extend(deep_dir(object.__class__))
   elif type(object) is types.ClassType:
      for base in object.__bases__:
         result.extend(deep_dir(base))

   return result

But you can't do it with normal dir().

Why do you need it? Maybe there is some better way.

-- 
Remco Gerlich