Why are the, dir () method and the _ _ dir__ () method different for a class?

check the documentation for the dir method, which has the following description:

If the object supplies a method named _ dir__, it will be used; otherwise
the default dir () logic is used and returns

that is, as long as the object itself has a _ _ dir__ method, the two should actually be the same. But try the following example and find that the two are not consistent:

class A(object):
    pass
    
print(dir(A))
print(A.__dir__(A))
The

_ _ dir__ method has some extra properties, such as _ _ mro__ , _ _ name__ , and so on. Why?

Jun.23,2021

your two print are not the same. The first one calls the _ _ dir__ method of A's metaclass, and the second one calls A's _ _ dir__ method.


I also took a look at the official document and your code. Your A does not customize the method of _ _ dir__. Of course, the two returns are different. Try this code of mine

.
class A(object):
    def __dir__(self):
        return ['a', 'b', 'c']


a = A()
print(dir(a))
print(A.__dir__(a))
Menu