Maison  >  Article  >  développement back-end  >  Comment trouver une méthode ou une propriété d’un objet en Python ?

Comment trouver une méthode ou une propriété d’un objet en Python ?

王林
王林avant
2023-09-17 16:01:02815parcourir

Comment trouver une méthode ou une propriété d’un objet en Python ?

Pour retrouver les attributs d'un objet, utilisez la méthode getarr() en Python. Pour vérifier si un attribut existe, utilisez la méthode hasattr(). Définissez les attributs à l'aide de la méthode setattr() en Python.

Accéder aux propriétés des objets

Exemple

Pour accéder aux attributs d'un objet nous utiliserons la méthode getattr() en 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'))

Sortie

Name = Amit
Age = 18

Accéder et définir les propriétés de la classe

Exemple

Dans cet exemple, pour définir l'attribut, nous utiliserons la méthode setattr().

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

Sortie

Tim
True
95
True

Méthode d'accès

Exemple

Dans cet exemple, nous apprendrons comment accéder aux méthodes -

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

Sortie

Tim
True
95
True
Hello from demo() function

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Cet article est reproduit dans:. en cas de violation, veuillez contacter admin@php.cn Supprimer