Jamie Balfour

Welcome to my personal website.

Find out more about me, my personal projects, reviews, courses and much more here.

Part 5.1Classes in Python

Classes are an essential part of any programming language in the object-oriented paradigm because of their relation to objects. This is because in an object-oriented language an object is often an instance of a class.

A class can be seen as being something of a blueprint for a person or a thing in the real-world. For example, a class named Person may have attributes (known as properties) such as their name, date of birth and favourite colour.

Whilst the Person class would not necessarily define these details itself, an instance of the class would.

Objects can often be represented by a syntax known as JSON very easily. For example, the instance of the Person classes called Bob might store the following details:

JSON
{
  "name"            : "Bob",
  "dob"             : "12-8-1994",
  "favourite-color" : "Purple"
}

Write down as many properties you would expect to see in a Car class.

An introduction to classes in Python

Python has one of the messiest implementations of classes of all object-oriented programming languages. There are several reasons for this but they will not be discussed in this course.

A Python class can be defined with the class keyword as shown below:

Python
class Person:
  # A person class
  fName = ""
  sName = ""

This class can then be instantiated (that is, an instance of the class is created) using the following code:

Python
peter = Person()
john = Person()

Using classes

The variables peter and john are both instances of the Person class. However, they both contain no data. To add data, the properties of the class, e.g. fName and sName need to be modified:

Python
peter = Person()
peter.fName = "Peter"
peter.sName = "Franks"

john = Person()
john.fName = "John"
john.sName = "Smith"

Printing the fName properties of these instances to the display yields the following results:

Peter
John

Classes can also define functions (known as methods) within them that can either give back data about the instance (a getter method or accessor method), or set data about the instance (a setter method or mutator method) or they can simply perform a task.

The example below shows this with a mutator and accessor function as well as a function which performs a task:

Python
class Person:
  # A person class
  fName = ""
  sName = ""

  def setForename(self, n):
    self.fName = n

  def setSurname(self, n):
    self.sName = n

  def getForename(self):
    return self.fName

  def getSurname(self):
    return self.sName

  def writeToFile(self, path):
    file = open(path, "w")
    file.write(self.fName)
    file.close()


peter = Person()
peter.setForename("Peter")
peter.setSurname("Franks")
peter.writeToFile("peter.txt")

john = Person()
john.setForename("John")
john.setSurname("Smith")
peter.writeToFile("john.txt")
Feedback 👍
Comments are sent via email to me.