The dir() function in python results in:
时间: 2024-11-05 10:32:20 浏览: 10
详解python 中in 的 用法
5星 · 资源好评率100%
The `dir()` function in Python is a built-in function that returns a list of names (attributes or methods) of an object, including those inherited from its parent class. It's primarily used for introspection, allowing developers to explore the contents of an object, such as its attributes, methods, or even its metaclass properties.
When called on an instance of a class, `dir()` displays the public members (methods and variables) that can be accessed by that instance. For example:
```python
class MyClass:
def __init__(self):
self.public_var = "Hello"
self.my_method()
my_instance = MyClass()
print(dir(my_instance))
```
This might output something like: `['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'my_method', 'public_var']`.
If `dir()` is called on a module, it will display the names of all the symbols available in that module.
In summary, `dir()` is a convenient tool for understanding what a particular object has to offer, whether it's an instance, class, or a module itself.
阅读全文