Mutator class methods are functions that change the value of an attribute. The most common type of
mutator method is called a setter.
You use a setter method to set the value of an attribute in the class. While not required, it’s somewhat
of a standard convention in Python coding to name setter mutator methods starting with set_, as in
this example:
Click here to view code image
def set_description(self, desc):
self.__description = desc
The set_ methods use two parameters. The first parameter is a special value called self. The
self parameter points the class to the current instance of the object. This parameter is required in
all class methods as the first parameter.
The second parameter defines a value to set as the attribute value for the instance. Notice the
assignment statement used in the method statement:
self.__description = desc
The attribute name is __description. Yet another de facto Python standard in OOP is to use two
underscores at the start of the attribute name to indicate that it shouldn’t be used by programs outside
the class definition.
By the Way: Private Attributes
Some object-oriented programming languages provide a feature called private
attributes. You can use private attributes inside the class definition but not outside the
class in the program code. Python doesn’t provide for private attributes; any attribute
you define can be accessed from any program. The two-underscore naming convention
just makes it obvious which attributes you prefer not to use outside the class definition.
The self keyword used in the attribute assignment is used to reference the attribute to the current
class instance.
You can also include other mutator methods that perform some type of calculations with the attributes.
For example, you could create a buy_Product() method for the Product class that changes the
inventory value of a product when a customer purchases it. That code would look something like this:
Click here to view code image
def buy_Product(self, amount):
self.__inventory = self.__inventory - amount
The mutator method still requires the self keyword as the first parameter, and it uses a second
parameter to provide data for the method. The assignment statement changes the __inventory
attribute value for the instance by subtracting the value sent as the second parameter.
Accessor Methods
Accessor methods are functions you use to access the attributes you define in a class. Creating special
methods to retrieve the current attribute values helps create a standard for how other programs use
your class object. These methods are often called getters because they retrieve the value of the