Attributes Annotations
Using annotations starting with @
symbol is a special way to define properties.
Write
@property
to defineget()
method;Write
@attribute.setter
to define theset()
method for the attribute.
We need to do that to explain to Python what these methods are going to be used for.
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class 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)
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
@property
and after that – setter@attribute.setter
;Both methods have the same name, that is equal to the attribute name;
Now, to access the private attribute
__age
outside the class, you can use thecat.age
expression;
War alles klar?
Danke für Ihr Feedback!
Abschnitt 2. Kapitel 3
Fragen Sie AI
Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen