Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How can I find the methods or attributes of an object in Python?
To find the methods or attributes of an object in Python, you can use several built-in functions. The getattr() method retrieves attribute values, hasattr() checks if an attribute exists, and setattr() sets attribute values. Additionally, dir() lists all available attributes and methods.
Using getattr() to Access Attributes
Example
The getattr() function retrieves the value of an object's attribute ?
class Student:
st_name = 'Amit'
st_age = '18'
st_marks = '99'
def demo(self):
print(self.st_name)
print(self.st_age)
print(self.st_marks)
# Create objects
st1 = Student()
st2 = Student()
# The getattr() is used here
print("Name =", getattr(st1, 'st_name'))
print("Age =", getattr(st2, 'st_age'))
Name = Amit Age = 18
Using hasattr() and setattr()
Example
The hasattr() function checks if an attribute exists, while setattr() creates or modifies attributes ?
class Student:
st_name = 'Tim'
st_age = '18'
def demo(self):
print("Hello from demo() function")
# Get existing attribute
print(getattr(Student, 'st_name'))
# Check if attribute exists
print(hasattr(Student, 'st_age'))
# Set new attribute
setattr(Student, 'st_marks', '95')
# Get newly set attribute
print(getattr(Student, 'st_marks'))
# Check if method exists
print(hasattr(Student, 'demo'))
Tim True 95 True
Using dir() to List All Attributes and Methods
Example
The dir() function returns a list of all attributes and methods available for an object ?
class Student:
st_name = 'Tim'
st_age = '18'
def demo(self):
print("Hello from demo() function")
# Create object
st1 = Student()
# List all attributes and methods
attributes = dir(st1)
print("Available attributes and methods:")
for attr in attributes:
if not attr.startswith('__'): # Skip special methods
print(f"- {attr}")
# Call the method
st1.demo()
Available attributes and methods: - demo - st_age - st_name Hello from demo() function
Comparison of Methods
| Function | Purpose | Returns |
|---|---|---|
getattr(obj, name) |
Get attribute value | Attribute value |
hasattr(obj, name) |
Check if attribute exists | Boolean |
setattr(obj, name, value) |
Set attribute value | None |
dir(obj) |
List all attributes/methods | List of strings |
Conclusion
Use dir() to discover all available attributes and methods of an object. Use getattr(), hasattr(), and setattr() to dynamically access, check, and modify object attributes at runtime.
