- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can I find the methods or attributes of an object in Python?
To find the attributes of an object, use the getarr() method in Python. To check if an attribute exist or not, use the hasattr() method. Set an attribute using the setattr() method in Python.
Access the attributes of an object
Example
To access the attributes of an object, we will use the getattr() method in Python −
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'))
Output
Name = Amit Age = 18
Access and set class attributes
Example
In this example, to set the attributes, we will use the setattr() method.
class student: st_name ='Tim' st_age ='18' def demo(self): print("Hello from demo() function") # The getattr() is used here print(getattr(student,'st_name')) # Returns true if object has attribute print(hasattr(student,'st_age')) # Set additional attribute st_marks setattr(student,'st_marks','95') # Get Attribute print(getattr(student,'st_marks')) # Checking for an attribute print(hasattr(student,'demo'))
Output
Tim True 95 True
Access methods
Example
In this example, we will learn how to access methods −
class student: st_name ='Tim' st_age ='18' def demo(self): print("Hello from demo() function") # The getattr() is used here print(getattr(student,'st_name')) # Returns true if object has attribute print(hasattr(student,'st_age')) # Set additional attribute st_marks setattr(student,'st_marks','95') # Get Attribute print(getattr(student,'st_marks')) # Checking for an attribute print(hasattr(student,'demo')) # Access methods using an object st1 = student() st1.demo()
Output
Tim True 95 True Hello from demo() function
Advertisements