Classes with private attributes
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.

class Pet:
def __init__(self, Name, Age):
self.__Name = Name
self.__Age = Age
def GetName(self):
return self.__Name
def GetAge(self):
return self.__Age
MyPet = Pet("Rex", 4)
print(MyPet.GetName(), "is", MyPet.GetAge())
__init__is the constructor. It runs when you writePet("Rex", 4)and stores each parameter in its attribute.- Paper 4 names attributes and methods in this style:
__Name,GetName.
Getters and setters
- A getter (
GetAge) returns the value of one attribute. It changes nothing. - A setter (
SetAge) changes one attribute. It can check the new value first and refuse a bad one. - A setter often returns
Truewhen it made the change andFalsewhen it refused.

class Pet:
def __init__(self, Name, Age):
self.__Name = Name
self.__Age = Age
def GetAge(self):
return self.__Age
def SetAge(self, NewAge):
if NewAge >= 0:
self.__Age = NewAge
return True
return False
MyPet = Pet("Rex", 4)
print(MyPet.SetAge(5), MyPet.GetAge())
print(MyPet.SetAge(-3), MyPet.GetAge())
- The output is
True 5, thenFalse 5. The setter kept the bad value out.
Private really means outside code cannot reach it
MyPet.__Nameoutside the class raises anAttributeError.- Inside the class's own methods,
self.__Nameworks normally.
class Pet:
def __init__(self, Name):
self.__Name = Name
def GetName(self):
return self.__Name
MyPet = Pet("Rex")
print(MyPet.GetName())
try:
print(MyPet.__Name)
except AttributeError:
print("__Name is private: use GetName()")
A list of objects
- A program often stores many objects in one list:
Pets = [], thenPets.append(Pet("Rex", 4)). Pets[1]is the second object, because Python lists start at index 0.Pets[1].GetAge()calls that object's method.- To find the oldest pet, loop over the list and compare the ages from the getters.
![Pets[0], Pets[1] and Pets[2] each hold one Pet object; Pets[1].GetAge() returns 9](/static/code/a-level-cs/objects-list.png)
class Pet:
def __init__(self, Name, Age):
self.__Name = Name
self.__Age = Age
def GetName(self):
return self.__Name
def GetAge(self):
return self.__Age
Pets = [Pet("Rex", 4), Pet("Mia", 9), Pet("Bo", 2)]
Oldest = 0
for Index in range(1, len(Pets)):
if Pets[Index].GetAge() > Pets[Oldest].GetAge():
Oldest = Index
print("Oldest:", Pets[Oldest].GetName())
Oldestkeeps the index of the oldest pet so far, so the name and the age always come from the same object.
In Cambridge pseudocode
- Pseudocode writes
PRIVATEandPUBLICin front of each attribute and method. The constructor is calledNEW.
CLASS Pet
PRIVATE Name : STRING
PRIVATE Age : INTEGER
PUBLIC PROCEDURE NEW(PName : STRING, PAge : INTEGER)
Name ← PName
Age ← PAge
ENDPROCEDURE
PUBLIC FUNCTION GetAge() RETURNS INTEGER
RETURN Age
ENDFUNCTION
ENDCLASS
MyPet ← NEW Pet("Rex", 4)
Common mistakes
| Wrong | Right | Why |
|---|---|---|
self.Name = Name |
self.__Name = Name |
without the two underscores the attribute is public |
def GetName(): |
def GetName(self): |
every method needs self first |
return __Name |
return self.__Name |
the attribute belongs to the object, so use self. |
print(MyPet.__Age) outside the class |
print(MyPet.GetAge()) |
private attributes are reached through methods |
| a setter that stores any value | test the value first | the point of a setter is to keep bad data out |
Now you try
- Use two underscores for every attribute and write a method for every value the test needs.
- Press Check answer to test your code.
Сложность 2/5 · 140 монет + небольшой бонус за первое завершение сегодня
Write a class Book with two private attributes, __Title и __Pages, set by the constructor Book(Title, Pages). Add the getters GetTitle() и GetPages().
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
Add a setter SetPages(NewPages) до Book. It stores NewPages and returns True only when NewPages is greater than 0. Otherwise it changes nothing and returns False.
Нажмите Запустить, чтобы увидеть результат здесь.
Сложность 3/5 · 200 монет + небольшой бонус за первое завершение сегодня
The list Books удерживает Book objects. Write a function Longest(Books) that returns the название of the book with the most pages. On a tie, return the first one.
Нажмите Запустить, чтобы увидеть результат здесь.