What's the difference between dir() and __dir__?

后端 未结 4 1669
我寻月下人不归
我寻月下人不归 2020-12-31 04:24

in python what\'s the difference between dir() function and __dir__ attribute in python?

&         


        
相关标签:
4条回答
  • 2020-12-31 04:37

    It's worth pointing out that the __dir__ on many objects cannot be customized, so if you call it directly there is no opportunity to place a shim/wrapper in there.

    It's easy to replace the builtin dir and give it some special powers if you need to. Tricks like this can be very useful when debugging.

    0 讨论(0)
  • 2020-12-31 04:41

    dir calls __dir__ internally:

    In [1]: class Hello():
       ...:     def __dir__(self):
       ...:         return [1,2,3]
       ...:     
    
    In [2]: dir(Hello())
    Out[2]: [1, 2, 3]
    
    0 讨论(0)
  • 2020-12-31 04:43

    The docs explain it:

    If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

    If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

    0 讨论(0)
  • 2020-12-31 04:45

    dir calls __dir__ method if it is present, from python documentation :

    dir([object])¶ Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

    If the object has a method named __dir__(), this method will be called and must return the list of attributes. This allows objects that implement a custom __getattr__() or __getattribute__() function to customize the way dir() reports their attributes.

    If the object does not provide __dir__(), the function tries its best to gather information from the object’s __dict__ attribute, if defined, and from its type object. The resulting list is not necessarily complete, and may be inaccurate when the object has a custom __getattr__().

    0 讨论(0)
提交回复
热议问题