Home » Tutorials » Python » Classes


Well, I’m not going to lie to you. The next few tutorials are going to be rather complicated if you have never had any experience with object oriented programming (OOP). Classes are awesome because of a few reasons. First, they help you reuse code instead of duplicating the code in other places all over your program. Classes will save your life when you realize you want to change a function. You will only change it in one spot instead of 10 different spots with slightly different code. Another important part of Classes is that they allow you to create more flexible functions. First, we need to get our hands dirty and start figuring out how to make a class.

Creating Classes in Python

class Calculator(object):
    #define class to simulate a simple calculator
    def __init__ (self):
        #start with zero
        self.current = 0
    def add(self, amount):
        #add number to current
        self.current += amount
    def getCurrent(self):
        return self.current

Now, I’m not going to be like everyone else and start bombing terminology at you. Quite frankly, object oriented programming is rather difficult for a beginner and throwing these abstract concepts at you is just going to make you learn slower and hate OOP. So, a class is kind of like a function. We just establish it using the class keyword and following it up with whatever we want to name our class. In our case, we are making a calculator, so that’s what I called it. How original! Next, we throw in the argument of object. This is just simply a class above this class. Don’t worry much about it. It involves some serious terminology to explain. So, just type it and we will talk about it later.

Next, we get into this little guy def __init__ (self):. Abstract concept time! Objects are made from classes. So, if we had a class named cake. We could make cake objects. However, whenever you make a cake it’s not the same as the previous cake you made. Sure, it may look like it and taste like it, but it’s not that identical cake. So, in our class we have instances so that we know that they are two different cakes. Why do we need this you ask? Well, let’s make two cakes from the same class. Now, I take a big bite out of one of the cakes. Now, you definitely want to know which cake is which right? That’s why instances are so important! So, def __init__ (self): just says let’s create an instance of this class. But, why do we pass in a parameter of self, you might ask. Well, it is pretty related to what we just discussed. Classes make objects and the functions in a class become the object’s methods. However, we do need to know which class function belongs to which instance of the class, so we just implicitly pass in the objects property of self (discussed further in later example). Finally, we get down into the heart of the initialize function. Where we use self.current to create an instance variable equal to zero. Woo! We are done with the toughest part.

Next stop is the add function. We just pass in self and another parameter called amount. Again, self is so we know which instance. The amount is hopefully some number that was passed in. Using our previous knowledge, we understand that we are just adding whatever the amount is to the current variable.

Last, but certainly not least, we move onto this idea of “getting” variables from a class. To get the value of our self.current variable, we should use the best practice of putting it in a function and then calling the function to get the value so that we don’t mix up our instances. We set up the function and pass in the instance, and just tell Python to return the value.

Using Classes in Python

from ClassOne import * #get classes from ClassOne file
myBuddy = Calculator() # make myBuddy into a Calculator object
myBuddy.add(2) #use myBuddy's new add method derived from the Calculator class
print(myBuddy.getCurrent()) #print myBuddy's current instance variable

In another file, we put in this code. Once we run it, we see it prints 2 to our screen. All of that work just to get the result of 2! Anyways, let’s break this guy down. First, I have assumed that both of your classes are in the Python directory. Next, we use from ClassOne, which basically gives Python a reference to which file we are talking about. Then, we polish the statement off with import *. It just means that we want all of the classes in the file. In our case, we only have one class, the Calculator class. Next, we create an Calculator object called myBuddy by assigning it to the Calculator class with myBuddy = Calculator() . Now, this gives myBuddy all of the functions and variables in the Calculator class. (Note: once myBuddy gets those variables and functions, we call them properties and methods). Since we already initialized myBuddy, it has a property of current, and we see that property as a variable called self.current in the Calculator class that is set to 0. So, now we just call myBuddy.add(2) method, which is the add function in our Calculator class. Put simply, this is just 0 + 2. Finally, we output our instance class variable self.current by using the myBuddy.getCurrent() that returns our variable.

Well done! That was a long one. Take a breather. That’s one of the toughest concepts in programming to wrap your mind around. Believe it or not, when you use strings, lists, dictionaries, etc., they all are made from classes. From here, you should take some time and study object oriented programming and attempt to apply it in Python.

Link/cite this page

If you use any of the content on this page in your own work, please use the code below to cite this page as the source of the content.

  • Stewart, Suzy. "Classes". After Hours Programming. Accessed on July 4, 2024. https://www.afterhoursprogramming.com/tutorial/python/classes/.

  • Stewart, Suzy. "Classes". After Hours Programming, https://www.afterhoursprogramming.com/tutorial/python/classes/. Accessed 4 July, 2024.

  • Stewart, Suzy. Classes. After Hours Programming. Retrieved from https://www.afterhoursprogramming.com/tutorial/python/classes/.

18 thoughts on “Classes”

  1. From the first topic to here, it was a really, really nice tutorial on python. I feel really attracted to the language already thanks to your tutorial. The way you explained everything was really clear and fun. Just wanted to thank you for this beautiful piece of work. Have a good day…

  2. @Antony

    Here is how I worked through this tutorial, and finally got it to work exactly like the examples:

    First I created the first example in IDLE as follows:

    class Calculator(object):
    def __init__(self):
    self.current = 0
    def add(self, amount):
    self.current += amount
    def getCurrent(self):
    return self.current

    ****note on the second line there needs to be a space after def and no space before (self)****

    From there I transferred it into the notepad app and saved it as ClassOne.py in my python directory.

    Then in IDLE, I was able to write this:

    >>> from ClassOne import*
    >>> myBuddy = Calculator()
    >>> myBuddy.add(2)
    >>> print(myBuddy.getCurrent())

    Took several tries, and I almost gave up to work on another area of Python, but finally figured it out. Keep at it!

  3. Terrific tutorial. I do wish that you would expand it, however. It seems to end rather abruptly with classes and objects. What can one do, especially online, with python?

  4. A little tricky had the same problem as Satya, but found that the def _init_(self) needed to be double underscores and a space added like this
    def __init__ (self). Yet the def getCurrent(self) didn’t need spaces.

  5. I think the parameter "self" is just like the "this" pointer in c++? When we use, add(self, amount), "self" already has its value (might be a address in memory), so add(2) means amount=2?

  6. I can’t get IDLE to recognize ClassOne. I suspect that it might be a problem with def __init__(self). Where are you supposed to put spaces?
    The other possibility that I see is that IDLE doesn’t recognize the proper path for the file. I’ve got IDLE for Python 2 and 3. Maybe this is causing the conflict? How would I specify the path to make sure I’ve go the right directory first?

  7. I get this error. What am I doing wrong?

    Traceback (most recent call last):
    File "./classes.py", line 4, in <module>
    myBuddy.add(2) #use myBuddy’s new add method derived from the Calculator class
    File "/home/traxaem/Desktop/Python/ClassOne.py", line 10, in add
    self.Current += amount
    AttributeError: ‘Calculator’ object has no attribute ‘Current’

  8. So I’m just a little confused here, for the first example do I right the classOne code into the Python GUI or do we put it into notepad(etc.), for the second example do I also do the same as the first.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.