Creating your own classes

Updated on 28 Dec 2022

Classes are a collection of data (attributes or properties) and methods (functions) that act on that data. In its basic form, it is a nice way of encapsulating related methods and that is what we’ll look at in this section.

creating quote class

The random_quote() function is pretty good, but lets encapsulate that into a class. We want to

  • retrieve a random_quote
  • retrieve all quotes
  • add a new quote
import random

class Quote:
    staticVar = 'this is a class variable'

    # this is a constructor
    def __init__(self):  
        self.quotes = [
            'git',
            'imbecile',
            'invented TIM',
            'need to ask yourself, what are we really trying to solve'
        ]    # instance variable

    def random_quote(self):
        return random.choice(self.quotes)

if __name__ == "__main__":
    print('this should be imported into a main application...')

Note: self is a special keyword that points to itself.

Using this class is similar to how we imported a function before.

import Quote

# 1st Quote is the filename
# 2nd Quote is the classname
# random_quote is the method in the Quote class

myQuotes = Quote.Quote() 
print(myQuotes.random_quote())

Constructor and Magic Methods

The _new magic method is called during creation, and will implicitly call init, which is where you would initialize your properties.

Other magic methods to consider include

  • del the destructor
  • add providing a method for the + operator
  • str convert your object to a string

Nuances

self is a special keyword that points to itself and is used to refer to internally defined attributes and methods. init is a special method that is used to initialize attributes. In other languages you might consider this to be the constructor. It is called automatically when the object is created. Notice that we define self.quotes in the init method, but we’re able to access it in random_quote()!

A class is like a blueprint, and we don’t execute the code until we’ve created an object. We create the object like this:

object = filename.classname()

We can also create more than 1 object of the same class.

object1 = filename.classname()
object2 = filename.classname()

Adding a few more methods

Let’s flesh out our class by adding the remaining functionality; retrieving all the quotes and adding a quote. Lets add the following to our Quote class

...
    def add_quote(self, new_quote):
        self.quotes.append(new_quote)

    def get_all_quotes(self):
        return self.quotes

Testing out these methods could be done with sample code like as follows:

import Quote

# 1st Quote is the filename
# 2nd Quote is the classname
# add_quote is the method of the Quote class
# get_all_quotes is the method of the Quote class, and returns a list

myQuotes = Quote.Quote() 

myQuotes.add_quote('added this myself!')
print(myQuotes.get_all_quotes())

classes - extended exercise

What do you think the output of the code below will be?

import Quote

myQuotes = Quote.Quote() 
myQuotes.add_quote('added this myself!')

myQuotes2 = Quote.Quote()
print(myQuotes2.get_all_quotes())