How to see the __name__ attribute of a class by using dir()
Peter Otten
__peter__ at web.de
Sat Oct 20 04:24:36 EDT 2012
Jennie wrote:
> The dir() built-in does not show the __name__ attribute of a class:
>
> >>> '__name__' in Foo.__dict__
> False
> >>> Foo.__name__
> 'Foo'
>
> I implementd my custom __dir__, but the dir() built-in do not want to
> call it:
>
> >>> class Foo:
> ... @classmethod
> ... def __dir__(cls):
> ... return ['python']
> ...
> >>> Foo.__dir__()
> ['python']
> >>> dir(Foo)
> ['__class__', '__delattr__', '__dict__', ...]
>
> Can someone tell me where is the problem? Thanks a lot in advance
Implementing __dir__ as an instance method works:
>>> class Foo(object):
... def __dir__(self): return ["python"]
...
>>> dir(Foo())
['python']
So if you want to customise dir(Foo) you have to modify the metaclass:
>>> class Foo:
... class __metaclass__(type):
... def __dir__(self): return ["python"]
...
>>> dir(Foo)
['python']
More information about the Python-list
mailing list