Python Class

A Python Class is an object that can hold information. It is a building block and corner stone of the Python language. In fact, Python is an Object Oriented Programming (OOP) language and classes are what make it so.

Classes are extremely useful for writing efficient clean code that is reusable. All of your favorite python libraries use classes to give you awesome functionality.

Within classes you can hold properties (like class variables) and methods (class functions). You can also have class inheritance — child and parent classes, but this is a lesson for another time.

In the example below, I’m creating a Student class that has a name and age property. The class part is just the template. We don’t actually create a Student object until the last line…Bob.

class Student():
  def __init__(self, name, age):
    self.name = name
    self.age = age
    
student1 = Student("Bob", 21)

Note: You may hear the word object get used. The person using this means a single instantiated instance of a class. Instantiated means it has been created.

Let’s take a look at a python class code sample


Python Class

DataIndependent - Class

Classes are objects that hold together information. Think of them as templates of objects that can have many properties or methods (class functions)

Let's look at a before & after of using classes.

Say we had 3 students with 3 properties each (name, grade, hometown). If we did this without classes. We would need to create 9 variables (3 students * 3 properties). But with classes, we will make one template, and store the information

Without Classes - The Long Way

In [1]:
student_1_name = "Bob"
student_1_grade = "Freshman"
student_1_hometown = "Sunnyvale"

student_2_name = "Sally"
student_2_grade = "Junior"
student_2_hometown = "San Francisco"

student_3_name = "Katie"
student_3_grade = "Senior"
student_3_hometown = "Mountain View"

That's a lot of variables to keep track of. But! There is an easier way with classes.

First let's create a student class then fill it in with our three students.

Notice this time we only have to watch out for 3 students and 3 variables.

In [4]:
class Student():
    def __init__ (self, name, grade, hometown):
        self.name = name
        self.grade = grade
        self.hometown = hometown
In [6]:
student1 = Student("Bob", "Freshman", "Sunnyvale")
student2 = Student("Sally", "Junior", "San Francisco")
student3 = Student("Katie", "Senior", "Mountain View")

Then we can call whichever variable or property we want!

In [7]:
student2.hometown
Out[7]:
'San Francisco'
In [ ]:
 

Link to code above

Check out more Python Vocabulary on our Glossary Page