The ABCs of Python: “def,” “class,” and leopards

This post is about the Python keyword def, not to mention class.


This is short for “define.” You use this word to tell the computer that you’re defining something called a function. As we discussed in the posts Um, What’s Your Function, Again? and Could You Pass the Delicious-Looking Plate of Parameters?, a function is a block of lego-like code that not only helps you keep your code orderly but makes it a lot easier to use it again in future programs (or use it multiple times in the same program).

With def, you’re telling the computer, “Hey, pay attention! You’ve gotta remember what we’re doing here so you can reference it when needed.” It’s sort of like when a choir conductor points to the lead singer, indicating, “It’s your turn to play the lead verse, and I mean now!” Here’s a super simple example of a function:

def leopard(): #name of the function and a bad rock n' roll pun
    print("snarl") #this is what it does
leopard() #this is how you call it


You might remember this keyword from the “Got Class?” post. Classes can be thought of as blueprints or templates that help you to create a variety of related Python objects. You might think of a  class as a sort of “uber function” that, among other things, helps create and control a bunch of other functions.

But that’s not entirely accurate. This is probably a better definition: “A Python class is like an outline for creating a new object. An object is anything that you wish to manipulate or change while working through the code.”

But maybe it’s best if you just create few classes. Here’s a quick bit of code to remind you how it works. This one is a slightly modified version from the one on the official Python site:

class Leopardy:
    kind = 'cat'      # class variable shared by all instances
    def __init__(self, name): = name #variable unique to each instance
d = Leopardy('Fangs')
e = Leopardy('Spot')
d.kind                  # shared by all leopards
e.kind                  # shared by all leopards                  # unique to d                  # unique to e

If you run that code, you should get two things printed out: “Fangs” and “cat.”

Featured image from Def_Leppard_Allstate_Arena_7-19-12 wikipedia Wikipedia: Image by AngryApathy