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

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

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

&         


        
4条回答
  •  Happy的楠姐
    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__().

提交回复
热议问题