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?

王林
Release: 2023-09-17 16:01:02
forward
887 people have browsed it

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'))
Copy after login

Output

Name = Amit
Age = 18
Copy after login

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'))
Copy after login

Output

Tim
True
95
True
Copy after login

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()
Copy after login

Output

Tim
True
95
True
Hello from demo() function
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template