1
help(dir):
dir([object]) -> list of strings        
If called without an argument, return the names in the current scope.  
Else, return an alphabetized list of names comprising (some of) the attributes  
of the given object, and of attributes reachable from it.  
If the object supplies a method named __dir__, it will be used; otherwise  
the default dir() logic is used and returns:  
  for a module object: the module's attributes.  
  for a class object:  its attributes, and recursively the attributes  
    of its bases.  
  for any other object: its attributes, its class's attributes, and  
    recursively the attributes of its class's base classes.

i found maybe there are problems in the help file of dir builtin function.for example:

class  AddrBookEntry(object):
   'address book entry class'
   def __init__(self,nm,ph):
     self.name=nm
     self.phone=ph
   def updatePhone(self,newph):
     self.phone=newph
     print 'Updated phone # for :' ,self.name

dir(AddrBookEntry('tom','123'))
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'name', 'phone', 'updatePhone']

1.dir() can list the method of object ,not only attributes
the updatePhone is method ,not attribute.

2.how can i know which is the attribute,which is method in the output of dir()?

1
  • 1
    What is your expected output here? Commented Jan 25, 2013 at 1:36

4 Answers 4

2
  1. Methods are attributes in Python.

  2. Check the various attributes on them. Methods have im_* attributes.

Sign up to request clarification or add additional context in comments.

3 Comments

or 2. [name for name in dir(whatever) if callable(getattr(whatever, name))]
callable() is unreliable since functions are first-class objects in Python, but are not methods.
I suppose you're talking about objects that implement __call__. While that's not so rare an edge-case, I still think what I said was a reasonable approximation of what OP was looking for. Filtering by 'method' in repr() or inspect.ismethod would be likewise unreliable.
2

You kind of get a feel for telling the difference, but methods are attributes, so the only way to be really sure is to check.

Here's a function that will break it down for you:

def dirf(obj=None):
    """Get the output of dir() as a tuple of lists of callables and non-callables."""
    d = ([],[])
    for name in dir(obj):
        if callable(getattr(obj, name, locals().get(name))):
            d[0].append(name)
        else:
            d[1].append(name)
    return d

inspect.getmembers has a nice shortcut for getting callable members:

from inspect import getmembers
getmembers(obj, callable)

but beware of its own predicates! inspect.ismethod will only be True for methods implemented in Python. Many core objects' methods ([].sort, for example) do not meet that criteria.

Comments

1

The help file is correct. In Python, methods are attached to classes (and instances of those classes) in exactly the same way as any other attribute. In order to distinguish a simple attribute from a callable one, you'll have to dereference it:

>>> type(AddrBookEntry('tom','123').phone)
<type 'str'>
>>> type(AddrBookEntry('tom','123').updatePhone)
<type 'instancemethod'>

Comments

-1

If you want to know the attributes of an object use the __dict__ attribute. E.g.:

>>> entry = AddrBookEntry('tom','123')
>>> entry.__dict__
{'name': 'tom', 'phone': '123'}

dir() is intended for debugging. Using it in production code is probably a bad idea. Exactly what it returns isn't very well defined.

3 Comments

-1 Dicts have keys and values. Attributes are something else, and all objects have attributes, whether or not they implement __dict__.
@kojori: Fundamentally objects implement getattribute and setattribute methods which are invoked when attributes are accessed. The Python object model has no concept of attribute, those are implemented at a higher level. If you create classes which inherit from object then instances of that class (and the class objects) will have attributes, and those attributes will be stored in a __dict__.
I see what you're saying, and why you're saying it, but OP asked specifically about dir, and your answer doesn't explain the difference between dir(obj) and obj.__dict__. That said, I would remove my downvote, but I need you to edit the answer before I can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.