A class can have one more variables (sometimes called properties). When you create objects each of those objects have unique values for those variables.

Class variables need not be set directly: they can be set using class methods. This is the object orientated way and helps you avoid mistakes.

Related course: Complete Python Programming Course & Exercises

Example

We create a class with a properties. From that class we create several objects.

1
2
3
4
5
6
class Friend:    
def __init__(self):
self.job = "None"

Alice = Friend()
Bob = Friend()

These objects do not have the property (job) set. To set it, we could set it directly but that’s a bad practice. Instead we create two methods: getJob() and setJob().

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Friend:
def __init__(self):
self.job = "None"

def getJob(self):
return self.job

def setJob(self, job):
self.job = job

Alice = Friend()
Bob = Friend()

Alice.setJob("Carpenter")
Bob.setJob("Builder")

print(Bob.job)
print(Alice.job)

Two objects are created, both of them have unique values for the property job:
getter setter

If you are a beginner, then I highly recommend this book.

Exercise

Try the exercises below

  1. Add a variable age and create a getter and setter
  2. Why would you use getter and setter methods?

After completing these continue with the next exercise.

Download answers