Programmation orientée objet intermédiaire en Python
Jake Roach
Data Engineer
class Student:
def __init__(self, student_name, major):
self.student_name = student_name
self.major = major
...
karina = Student("Karina", "Literature")
student.residence_hall # Tentative d'accès à un attribut inexistant
...
AttributeError: 'Student' object has no attribute 'residence_hall'
# Rest of the class definition above
def __getattr__(self, name):
# Implement logic here
...
L'espace de noms d'un objet est l'ensemble des attributs associés à cet objet
__getattr__() s'exécute lorsqu'on tente d'accéder à n'IMPORTE QUEL attribut en dehors de l'espace de noms de l'objet
nameAttributeErrorclass Student:
def __init__(self, student_name, major):
self.student_name = student_name
self.major = major
def __getattr__(self, name):
print(f"""{name} does not exist in this object's namespace, try setting
a value for {name} first""")
karina.residence_hall # Réessayez de récupérer l'attribut residence_hall
residence_hall does not exist in this object's namespace, try setting a value for
residence_hall first
__setattr__() est une méthode magique exécutée quand un attribut (nouveau ou existant) est défini ou mis à jour
__init__()name (nom) et value__dict__ de l'objet$$
$$
Contrôler les modifications d'attributs, valider, transformer
# Rest of the class definition above
def __setattr__(self, name, value):
# Implement logic here
...
# Use __dict__ to create/update
# the attribute
self.__dict__[name] = value
__dict__ stocke tous les attributs de l'objet ; il peut servir à lire et écrire des données
class Student:
def __init__(self, student_name, major):
self.student_name = student_name
self.major = major
def __setattr__(self, name, value):
# If value is a string, set the attribute using the __dict__ attribute
if isinstance(value, str):
print(f"Setting {name} = {value}")
self.__dict__[name] = value
else: # Otherwise, raise an exception noting an incorrect data type
raise Exception("Unexpected data type!")
# Définir un attribut avec une valeur de type 'str'
karina.residence_hall = "Honors College South"
print(karina.residence_hall)
Setting residence_hall = Honors College South
Honors College South
# Définir un attribut avec une valeur de type 'int'
karina.student_id = 19301872
...
raise Exception("Unexpected data type!")
Exception: Unexpected data type!
class Student:
...
def __getattr__(self, name):
# Set the attribute with a placeholder
self.__setattr__(name, None)
return None
def __setattr__(self, name, value):
if value is None: # Print a message denoting a placeholder
print(f"Setting placeholder for {name}")
self.__dict__[name] = value # Set the attribute
Programmation orientée objet intermédiaire en Python