Python Classes

It has taken me quite a while to begin to visualise and understand how classes work in Python. The thing with learning is that you can look at the same thing for days, weeks and months on end and then one day it randomly starts to make sense. This is completely normal and it appears to be how most people learn. I was recently creating a Django application by following along with a tutorial on Djangogirls.org  and suddenly classes in Python started to make a little more sense to me. I decided I would write about it today in order to help solidify the little bit of insight I had around classes in Python.

There are two key concepts that classes in Python possess - properties and methods.

Properties

Properties are the words you would use to describe the class. Let's say that you want to create a class for Blog posts. The properties are the typical things that every blog post will have in common. When you think of a typical blog post you will notice that each blog post will typically have a title field, a body field for the content of the post, an author field and a date time field. So the Blog Post class properties would look like this:

 

Blog Post

title
body
author
date and time

 

Methods

The methods are the typical actions that would be carried out on the class. In our example of the blog post we need to start thinking about common actions that would be carried out on blog posts. Typical actions for blog posts would be create, delete and save.

The methods on the Blog Post class would look like this.

Blog Post

create()
delete()
save()

Methods in Python contain executable code within them to carry out the action. The parentheses denote the fact that a function will be executed when the method is called.

I hope this helps to make the properties and methods within a typical Python class a little clearer to you.