Bỏ qua nội dung

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.
  • Bundling the data and the methods that operate on it inside a class is called encapsulation. Methods can validate values before storing them.

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

Đăng nhập hoặc tạo tài khoản

IGCSE, A-Level & AP