Home >Backend Development >Python Tutorial >How to find a method or property of an object in Python?

How to find a method or property of an object in Python?

王林
王林forward
2023-09-17 16:01:02894browse

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.

Accessing the properties 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

Accessing and setting class attributes

Example

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'))

Output

Tim
True
95
True

Access method

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

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete