Python-dir () function
Dir () function
Chinese description:
You can use the built-in dir function to list module-defined identifiers. Identifiers include functions, classes, and variables.
When you provide a module name for dir (), it returns the name list defined by the module. If no parameter is provided, it returns the name list defined in the current module.
First, let's take a look at using dir on the input sys module. We can see that it contains a huge list of attributes.
Next, we will use it instead of passing parameters to the dir function -- by default, it returns the attribute list of the current module. Note that the input module is also part of the list.
To observe the role of dir, we define a new variable a and assign it a value, and then test dir. we observe that the above values are added to the list. We use the del statement to delete the variables/attributes of the current module. this change is again reflected in the dir output.
Note about del-this statement is used to delete a variable/name after running. In this example, del a, you will no longer be able to use variable a -- it is as if it has never existed before.
Version:
This function is supported in all versions and is still available in python3.
Sample code:
>>> import struct>>> dir() # show the names in the module namespace['__builtins__', '__doc__', '__name__', 'struct']>>> dir(struct) # show the names in the struct module['Struct', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '_clearcache', 'calcsize', 'error', 'pack', 'pack_into', 'unpack', 'unpack_from']>>> class Shape(object): def __dir__(self): return ['area', 'perimeter', 'location']>>> s = Shape()>>> dir(s)['area', 'perimeter', 'location']
English description:
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 __().
The default dir () mechanic behaves differently with different types of objects, as it attempts to produce the most relevant, rather than complete, information:
If the object is a module object, the list contains the names of the module's attributes.
If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
Otherwise, the list contains the object's attributes 'names, the names of its class's attributes, and recursively of the attributes of its class's base classes.