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

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

def

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

class

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):
        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
d.name                  # unique to d
e.name                  # unique to e
print(d.name)
print(d.kind)

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

Published by

Mark R. Vickers

I am a writer, analyst, futurist and researcher. I've spent most of my working life as an editor and manager for research organizations focusing on social, business, technology, HR and management trends. But, perhaps more to the point for this blog, I'm curious about the universe and the myriad, often mysterious relationships therein.

Leave a Reply