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

Got Class?

On how to use classes in Python

Here are the metaphors I use to understand Python’s functions, modules, methods and classes:

Functions are like individual legos. Once you’ve created them, you can snap them in and out as needed to create working code.

Modules are sort of like prefab buildings that you have (or someone else has) built, in part, with those legos. You can add these entire prefabs to some larger construction project, or you can just scavenge some bits and pieces from a prefab and add it the construction project.

Modules are just Python files that contain relatively normal programs that are useful and can be utilized as often as you like. A module can have definitions of variables, functions, and even classes. You use “import” to bring modules – or pieces of modules – into whatever code you’re writing.

Methods are the same as functions, more or less. Except for the fact that they live “inside” classes. But, then, what in the heck are classes?

Classes are the blueprints, a metaphor I took from Steven Thurlow. He writes that a class “isn’t something in itself, it simply describes how to make something. You can create lots of objects from that blueprint – known technically as an instance.”

That sounds nifty, right? First you have legos, then prefabs made of legos, and then blueprints to keep it all organized.

Except this blueprint is also a bit like instructions that you put into a virtual 3-D printer. That is, the class both organizes and helps produce objects, all of which have similar characteristics and functions (or methods).

But enough metaphors for now. Let’s build a class, or draw a blueprint, or whatever works for you.

Step One: Decide what you want your overarching structure to cover. I’ve decided to build a dog, sort of.

Step Two: Next do the designing. In this case, we’re going to keep it somewhat basic but not so basic that you can’t see any nuances. The comments I’ve left explain how I see things.

Step Three: Create stuff (i.e., instances) based on your blueprint (i.e., class):

class Dog: #creates class called "Dog"

    def __init__(self, breed, height, weight, length, color):

        The code line above is a method common to classes. 
        Based on how you call the function, Python can 
        figure out what "self" is, so you don't need to 
        put it in among the parameters. You only need to 
        pass in the values called breed, height, weight, 
        length, and color
        self.breed = breed
        '''The line above makes sure that the program knows 
        that the value "breed" is going to be passed as 
        self.breed. Self is a placeholder for whatever 
        you decide to use. In this case, self is a 
        placeholder for 'Hank', as you can see below. The 
        same principle applies to the four other parameters 
        directly below'''
        self.height = height
        self.weight = weight
        self.length = length
        self.color = color
    def bark (self, sound):
        This adds a new method call "bark". When you call it, 
        it prints out whatever word you've put in as a parameter
        print (sound)
Hank = Dog('labrador', '24', '100', '36', 'yellow')
Here we are assigning the name Hank to Dog with these five values. As you can see, we don't need to put in a value for self. This is an example of how we are using a class to create an 'instance' named Hank. 

print("This is Hank's breed: " + Hank.breed + ". And here is his weight: " + str(Hank.weight)) 
print("Oh yeah, and here is his length: " + str(Hank.length)) 
In the lines above, we are printing out three specific values associated with Hank. This all hinges on what the blueprint describes in the class. We are putting some actual objects in based on that blueprint 

Hank.bark("bow wow") 
print("Really? Bow wow? You couldn't get more imaginative than that, you shmuck?") 
Hank.bark("How about wan-wan, as the Japanese dogs say?") 
Here we are calling the method of def bark(self, sound) in a couple of ways. 

And here’s how this stuff prints:

This is Hank’s breed: labrador. And here is his weight: 100
Oh yeah, and here is his length: 36
bow wow
Really? Bow wow? You couldn’t get more imaginative than that, you shmuck? How about wan-wan, as the Japanese dogs say?

Okay, I think that’s about right. I should also mention that one class can inherit features from another class. It’s almost as if such classes are part of a family tree and they all share the same DNA/bloodline. But, if you’re a beginner, then your mind is probably already blown, so we won’t bother with inheritance for now.

PS –  However, if you want to learn more about classes and inheritance immediately, I can recommend the following sources of information:

An Introduction to Classes and Inheritance (in Python) on Classes

Python from Scratch: Object Oriented Programming

Featured image: Hank by Cyndi Vickers