## Definition
A [[public]] [[method]] that modifies an [[object]]'s [[object state|state]] by changing the value of an [[attribute]].
*Noun.*
> Make a setter for the balance attribute as it allows you to enforce validation rules—customers should not have a negative balance.
## Characteristics
- Used in [[object-oriented programming]];
- provides controlled write-access to a specific attribute;
- supports [[encapsulation]] by providing controlled access to hidden data—thus modifying a specific part of the object's state;
- enables enforcement of validation rules for attribute values;
- typically used to modify the value of a [[private]] attribute;
- has an identifier that is, by convention, prefixed with `set`, e.g., `set_balance()`;
- can return the value of the attribute just modified.
## Examples
### `set_balance()`
```python
class BankAccount:
def __init__(self, p_id, p_balance):
self.id = p_id
# calling the setter enforces validation rules at creation
self.set_balance(p_balance)
# setter
def set_balance(self, p_balance):
if p_balance < 0:
raise ValueError("Balance cannot be negative")
else:
self.__balance = p_balance
return self.__balance
```
## Non-examples
### Directly modifying a public attribute
Directly modifying a public attribute is not a setter as it does not involve the use of a method.
```python
class Student:
...
shazia = Student("Shazia", 17)
shazia.name = "Sharna" # does not use a setter
```
### Methods that modify attributes with derived values
Methods that first derive a value before modifying an attribute are not setters.
```python
class BankAccount:
...
# not a setter
def deposit(self, p_amount):
if p_amount > 0:
self.__balance = self.__balance + p_amount
```
### Methods that modify more than one attribute
Setters only ever modify a single attribute.
```python
class BankAccount:
...
def close(self):
self.__balance = 0
self.status = "Closed"
```