Attributes Annotations
Using annotations starting with @ symbol is a special way to define properties.
- Write
@propertyto defineget()method; - Write
@attribute.setterto define theset()method for the attribute.
We need to do that to explain to Python what these methods are going to be used for.
1234567891011121314151617181920212223class Cat: def __init__(self, name = 'Kitty', age = 1): self.name = name self.__age = age self.__number_of_legs = 4 @property def age(self): return self.__age @age.setter def age(self, age): if isinstance(age, int) and 0<=age<=30: self.__age = age else: print('Invalid value of attribute age') cat = Cat('Maggie', 3) # Adding the wrong value cat.age = -100 cat.age = 5 print(cat.age)
Note
- First, define getter
@propertyand after that – setter@attribute.setter; - Both methods have the same name, that is equal to the attribute name;
- Now, to access the private attribute
__ageoutside the class, you can use thecat.ageexpression;
Tout était clair ?
Merci pour vos commentaires !
Section 2. Chapitre 3
Demandez à l'IA
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion
Suggested prompts:
Posez-moi des questions sur ce sujet
Résumer ce chapitre
Afficher des exemples du monde réel
Génial!
Completion taux amélioré à 7.69
Attributes Annotations
Glissez pour afficher le menu
Using annotations starting with @ symbol is a special way to define properties.
- Write
@propertyto defineget()method; - Write
@attribute.setterto define theset()method for the attribute.
We need to do that to explain to Python what these methods are going to be used for.
1234567891011121314151617181920212223class Cat: def __init__(self, name = 'Kitty', age = 1): self.name = name self.__age = age self.__number_of_legs = 4 @property def age(self): return self.__age @age.setter def age(self, age): if isinstance(age, int) and 0<=age<=30: self.__age = age else: print('Invalid value of attribute age') cat = Cat('Maggie', 3) # Adding the wrong value cat.age = -100 cat.age = 5 print(cat.age)
Note
- First, define getter
@propertyand after that – setter@attribute.setter; - Both methods have the same name, that is equal to the attribute name;
- Now, to access the private attribute
__ageoutside the class, you can use thecat.ageexpression;
Tout était clair ?
Merci pour vos commentaires !
Section 2. Chapitre 3