Home >Backend Development >Python Tutorial >How to find a method or property of an object in Python?
To find the attributes of an object, use the getarr() method in Python. To check if an attribute exists, use the hasattr() method. Set attributes using the setattr() method in Python.
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'))
Name = Amit Age = 18
In this example, to set the attribute, 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'))
Tim True 95 True
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()
Tim True 95 True Hello from demo() function
The above is the detailed content of How to find a method or property of an object in Python?. For more information, please follow other related articles on the PHP Chinese website!