Python中__dir__方法的具体实现及查询方式
Awesome question! You're right that the _dir_object function just delegates to the object's __dir__ method—so let's dig into how to find the actual implementation of __dir__ for different types of objects in CPython.
How to Find __dir__ Implementations in CPython
The implementation of __dir__ varies depending on what kind of object you're dealing with. Here's how to track it down:
1. Built-in Types (like list, dict, str)
For core Python types, their __dir__ methods are implemented in C. Follow these steps:
- Navigate to the
Objects/directory in the CPython repo—each built-in type has its own dedicated file (e.g.,listobject.cfor lists,dictobject.cfor dicts). - Locate the
PyTypeObjectstruct for the target type (e.g.,PyList_Typefor lists). Look for thetp_dirfield—this points directly to the C function that implements__dir__for that type. - Search for the function name linked to
tp_dirto view the full implementation code.
For example:
- For
list,PyList_Type.tp_dirpoints tolist_dir. This function collects standard list methods, plus any extra attributes stored in the list instance's__dict__(common if you've subclassedlistand added custom attributes). - If a type doesn't define a custom
tp_dir, it falls back to the genericPyObject_Dirfunction (inobject.c), which handles gathering attributes from the object's class hierarchy and its instance__dict__.
2. Custom Python Classes
- If you've explicitly defined a
__dir__method in your Python class, the implementation is right there in your code—no digging needed! - If you haven't overridden
__dir__, your class inherits it from its parent class. For most classes, this eventually traces back to the baseobjectclass's__dir__, implemented in theobject_dirfunction inobject.c. This function:- Collects attributes from the object's instance
__dict__ - Recursively gathers attributes from the class and all its base classes
- Deduplicates and sorts the combined list before returning it
- Collects attributes from the object's instance
3. Extension Types (C-written third-party libraries)
For types from C-based third-party extensions, you'll need to inspect the library's source code. Find the PyTypeObject struct for the target type, check its tp_dir field, then look up the corresponding function implementation in the library's codebase.
Quick Deep Dive: object.__dir__ Logic
Since most default __dir__ implementations rely on object_dir, here's a simplified breakdown of its core logic:
The
object_dirfunction first fetches the object's class, then walks up the inheritance chain to collect all class-level attributes. It then adds any keys from the object's__dict__(if the object supports instance dictionaries). Finally, it sorts and deduplicates the combined list to produce the final set of names you see when callingdir().
内容的提问来源于stack exchange,提问作者laike9m

