dir() / vars() / getattr()
Built-in functions for dynamically inspecting, retrieving, and setting attributes and methods on objects. Useful for debugging and dynamic programming.
Syntax
# Returns a list of attribute names and method names of the object. dir(object) # Returns the __dict__ attribute of the object (a dictionary of attribute names and values). vars(object) # Retrieves the value of a named attribute from an object. getattr(object, name, default) # Sets the value of a named attribute on an object. setattr(object, name, value) # Checks whether an object has a named attribute. hasattr(object, name) # Deletes a named attribute from an object. delattr(object, name)
Function list
| Function | Description |
|---|---|
| dir(obj) | Returns a list of attribute names and method names of the object. Called without arguments, it returns a list of names in the current scope. |
| vars(obj) | Returns the object's __dict__. Lets you inspect an instance's attributes and their values as a dictionary. |
| getattr(obj, name, default) | Retrieves the value of an attribute specified by name as a string. Returns the default value if the attribute does not exist. |
| setattr(obj, name, value) | Sets the value of an attribute specified by name as a string. If the attribute does not exist, it is created. |
| hasattr(obj, name) | Returns True if the object has an attribute with the given name. |
| delattr(obj, name) | Deletes the attribute with the given name from the object. |
Sample code
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}."
p = Person("Taro", 20)
# Use dir() to inspect the attributes and methods of the object.
attrs = dir(p)
# Includes special methods like __init__ and __str__, as well as name, age, and greet.
# Filter out special methods starting with __ (dunder) before displaying.
public_attrs = [a for a in dir(p) if not a.startswith("_")]
print(public_attrs) # ['age', 'greet', 'name']
# Use vars() to get the instance's attributes as a dictionary.
print(vars(p)) # {'name': 'Taro', 'age': 20}
# Use getattr() to retrieve an attribute value by name as a string.
attr_name = "name"
print(getattr(p, attr_name)) # Taro
print(getattr(p, "height", "unknown")) # unknown (default value)
# You can also retrieve a method with getattr() and call it.
greet_method = getattr(p, "greet")
print(greet_method()) # Hello, I'm Taro.
# Use setattr() to dynamically update an attribute value.
setattr(p, "age", 21)
print(p.age) # 21
# Dynamically add a new attribute.
setattr(p, "city", "Tokyo")
print(p.city) # Tokyo
# Use hasattr() to check whether an attribute exists before accessing it.
if hasattr(p, "email"):
print(p.email)
else:
print("No email address is registered.")
# Use delattr() to remove an attribute.
delattr(p, "city")
print(hasattr(p, "city")) # False
Overview
These functions provide Python's reflection capabilities. Because attribute names can be specified dynamically as strings, they are useful in programs that manipulate object attributes based on configuration files or user input.
『hasattr()』internally calls 『getattr()』and checks whether an exception is raised. If a property has side effects (such as database access or computation), simply calling 『hasattr()』may trigger that logic. In such cases, wrapping the attribute access in a try-except block is safer.
The result of 『dir()』includes inherited attributes and methods. To inspect only the attributes defined by the class itself, access the class's 『__dict__』directly with 『vars(ClassName)』. For type checking, see 『type() / isinstance()』.
If you find any errors or copyright issues, please contact us.