Get and Set
Getter and setter are methods for non-direct access to the attributes:
get()
( getter ) returns the value of the private attribute;set()
( setter ) sets the value.
These methods are called properties.
You can implement them by defining two additional methods:
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class Cat:
def __init__(self, name = 'Kitty', age = 1):
self.name = name
self.__age = age
self.__children = 0
# Getter
def get_age(self):
return self.__age
# Setter
def set_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)
# Wrong value
cat.set_age(-23)
cat.set_age(8)
print(cat.get_age())
12345678910111213141516171819202122class Cat: def __init__(self, name = 'Kitty', age = 1): self.name = name self.__age = age self.__children = 0 # Getter def get_age(self): return self.__age # Setter def set_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) # Wrong value cat.set_age(-23) cat.set_age(8) print(cat.get_age())
Note
We added data validation inside the set_age()
method. Only the correct integer value can be assigned to the attribute.
Tout était clair ?
Merci pour vos commentaires !
Section 2. Chapitre 2
Demandez à l'IA
Posez n'importe quelle question ou essayez l'une des questions suggérées pour commencer notre discussion