Passer au contenu

Classes with private attributes

English

Private attributes keep the data safe

  • In Paper 4, every attribute of a class is private. In Python you mark it with two underscores: self.__Name.
  • Code outside the class cannot read or change MyPet.__Name. It must call one of the class's public methods.
  • Keeping the data inside and the methods outside is called encapsulation. It stops other code from storing a bad value.

A Pet object holds the private attributes __Name and __Age; outside code reaches them only through the public methods GetName() and SetAge(); MyPet.__Name gives an AttributeError

Se connecter ou créer un compte

IGCSE, A-Level & AP