PythonBuilt-in functions
dir()
Returns a list of the names of an object’s attributes and methods.
- Returns
- A sorted list of strings.
Example
#Python
class Player:
def __init__(self):
self.level = 1
def level_up(self):
self.level += 1
names = [name for name in dir(Player()) if not name.startswith("_")]
print(names)
print("upper" in dir("text"))Resultsaved result, you can check it
['level', 'level_up']
True
Definition and usage
#The dir(object) function returns a sorted list of the attribute and method names available on an object. It's a quick way to check what you can do with it, for example which methods a string or a list has.
The list also includes special double-underscore names, like __len__. It is usually worth filtering them out to see the methods meant for direct use.
Called with no argument, it returns the names defined in the current scope, which helps you check what variables exist at that point in the program.
Syntax
#Syntax
dir(object)Parameters
#object
optional
The object whose attributes you want to see.
Good practices
#- Filter out names starting with an underscore to see only public methods.
- For the description of a specific method, use
help(), e.g.help(str.split).
Related entries
#- help()Displays the built-in documentation for an object, function, or module.
- type()Returns the type of an object.
- classDefines a class: a template for objects that combines data with the functions that act on it.
- getattr()Reads an object’s attribute by a name given as a string, optionally with a default value.
- hasattr()Checks whether an object has an attribute or method with the given name. Returns True or False.
Spotted a mistake or missing an example? Write to us.