Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Attributes Annotations | Encapsulation
Object-Oriented Programming in Python

bookAttributes Annotations

Using annotations starting with @ symbol is a special way to define properties.

  • Write @property to define get() method;
  • Write @attribute.setter to define the set() method for the attribute.

We need to do that to explain to Python what these methods are going to be used for.

1234567891011121314151617181920212223
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)
copy

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 the cat.age expression;
question mark

Сhoose the wrong option.

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 3

Spør AI

expand

Spør AI

ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

Suggested prompts:

Still meg spørsmål om dette emnet

Oppsummer dette kapittelet

Vis eksempler fra virkeligheten

Awesome!

Completion rate improved to 7.69

bookAttributes Annotations

Sveip for å vise menyen

Using annotations starting with @ symbol is a special way to define properties.

  • Write @property to define get() method;
  • Write @attribute.setter to define the set() method for the attribute.

We need to do that to explain to Python what these methods are going to be used for.

1234567891011121314151617181920212223
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)
copy

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 the cat.age expression;
question mark

Сhoose the wrong option.

Select the correct answer

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 3
some-alt