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 |
class 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 |
class Friend: |
Two objects are created, both of them have unique values for the property
job:
If you are a beginner, then I highly recommend this YouTube Python Playlist.
Exercise
Try the exercises below
- Add a variable age and create a getter and setter
- Why would you use getter and setter methods?
After completing these continue with the next exercise.