Format :dir
([object])
There is no argument , Returns the list of names in the current local scope .
With arguments , Returns a list of valid properties for a parameter object .
because python Everything is an object , all object Object can be a module , type , class , function , Method , Properties, etc .
Returns the list of names in the current local scope
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>>
Returns a list of valid properties for a parameter object
>>> import string
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_sentinel_dict', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
>>>
Be careful :
dir() By default, a list of all attributes and methods of the object will be output , Contains double underlined “__” The beginning and the end , Private methods that cannot be called externally . For ease of reading , We need to not show these special members , Here are two ways .
(1) If the object has __all__ Variable , You can use it directly , As in the above example, you can use string.__all__
>>> import string
>>> dir(string)
['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_sentinel_dict', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
>>> string.__all__
['ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace', 'Formatter', 'Template']
>>>
(2) Use string method str.startswith(), Filter out output lists that contain double underscores “__” Private methods at the beginning and end .
import string
# Do not display special members of the object
lst = [i for i in dir(string) if not i.startswith('_')]print(lst)
-----------------------------------------------------------------------------------
Running results :
['Formatter', 'Template', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']
refence:
Built in functions — Python 3.8.12 file