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

bookGet 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:

12345678910111213141516171819202122
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())
copy

Note

We added data validation inside the set_age() method. Only the correct integer value can be assigned to the attribute.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 2

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

bookGet and Set

Sveip for å vise menyen

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:

12345678910111213141516171819202122
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())
copy

Note

We added data validation inside the set_age() method. Only the correct integer value can be assigned to the attribute.

Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 2
some-alt