This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Encapsulation

Setter methods

face Josiah Wang

Let’s say that VainPerson now also allows someone to change its name. However, VainPerson will only allow their name to be changed if they like the sound of the new name. The name must also always be stored in uppercase (VainPerson is upper-class after all!)

Again, you can allow an outsider to modify your non-public attributes in a controlled manner via a method. Such methods are usually called setter methods in OOP.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class VainPerson:
    def __init__(self, name):
        self.set_name(name)

    def get_name(self):
        return f"Your Most Honourable Excellency {self.__name}"

    def set_name(self, new_name):
        if self.likes_name(new_name):
            self.__name = new_name.upper()
        else:
            if self.__name is None:
                # Just so we have a default name
                self.__name = "JOSIAH"
            else:
                print("I doth not liketh yond nameth. Off with thy headeth!")

    def likes_name(self, name):
        if name.upper() in ["EDWARD", "VICTORIA", "WILLIAM", "GEORGE",
                            "ELIZABETH", "JOSIAH"]:
            return True
        else:
            return False

lovely_person = VainPerson("Edward")
print(lovely_person.get_name()) # Your Most Honourable Excellency EDWARD
lovely_person.set_name("Snake") # I doth not liketh yond nameth. Off with thy headeth!
print(lovely_person.get_name()) # Your Most Honourable Excellency EDWARD
lovely_person.set_name("george")
print(lovely_person.get_name()) # Your Most Honourable Excellency GEORGE
lovely_person.__name = "Elizabeth"    # __name is non-public. NOT set to "Elizabeth"
print(lovely_person.get_name()) # Your Most Honourable Excellency GEORGE

The set_name() method (Line 8) allows an outsider to set the __name attribute without exposing it, but in a controlled manner. I have also updated Line 3 which also uses the method to set the name correctly, rather than setting self.__name = name directly in the constructor.

In Line 26, you can see that __name is stored in uppercase.

Line 27 does not update __name because VainPerson does not like it!

Line 29 is successful, so __name is now "GEORGE".

Lines 31-32 are just to demonstrate my point from the previous page, that lovely_person.__name is a new attribute, and is different from the name-mangled self.__name in the definition. So the ‘real’ __name is still "GEORGE".