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

Could You Pass the Delicious-Looking Plate of Parameters?

More on Python functions, parameters, values and stuff

Last time around we started chatting about functions: that is, the legos of the Python universe. You always start a function with the word “def” followed by the name of the function, followed by parentheses and a colon. In other words:

def NameOfFunction ():

Sometimes there will something inside the parentheses. If so, that’s your “parameter.” In the world of Python, parameters and arguments are pretty much used interchangeably, but, technically, parameters are the variables and arguments are the values you give those variables.

If I write “height = 6,” then height is the variable and 6 is the value.

Anyway, a parameter sits beside the function and is often integral to the work it does, sort of like the chocolate chips in a cookie batter. To get an idea of how this works, check out the super simple code below. In this case, the name of the function is “theBatter” and the name of the parameter is “chips.” :

def theBatter(chips):
    return (chips)

All this does is crank out chips. That is, it cranks out whatever string is placed into parentheses next to the name of the function. I say that it “cranks out” but you don’t actually see the chips that it cranked out unless you tell Python to print them.

How to explain this? Let’s say somebody asks you to calculate 2 + 2. You do it in your head but don’t say anything. The answer is “returned” in your head. Then the person asks you to write the answer down. So you do, printing out “4”.

That’s how it works in Python in this case. Once the function runs, it “returns” the answer but the answer remains in Python’s “mind.” You don’t see the answer till you tell it to print.

Now, let’s actually use (or “call,” as they say) the function described above a couple of times and print out the results:

firstVision = theBatter ('Envision this string as filled with chocolate chips and being poured into batter')
secondVision = theBatter ("Not enough chips yet? That's okay. Pour this string of chips into the function as well")
print (firstVision)
print (secondVision)

Note that we placed a literal string of characters that discussed chocolate chip cookies between the parentheses. If you run this code, here’s what you should get:

Envision this string as filled with chocolate chips and being poured into batter

Not enough chips yet? That’s okay. Pour this string of chips into the function as well

Okay, now let’s do something moderately harder. Write this into a new program.

pecans1 = 50
pecans2 = 150
chips1 = 60
chips2 = 120
def yumFactor (ingredient1, ingredient2):
     total = ingredient1 + ingredient2
     return total
todaysCookies = yumFactor(pecans1, chips2)
tomorrowsCookies = yumFactor (pecans2, chips1)
print ("The yum factor for today's cookies is " + str(todaysCookies))
print ("The yum factor for tomorrow's cookies is " + str(tomorrowsCookies))

So, what’s happening here?

First, we assign some values to some variables. For example,  pecans1 is a variable that has a value of 50.

Second, we write a function called yumFactor. It takes two parameters: ingredient1 and ingredient2. All the function really does is add the values of those two parameters together and then give you the sum total.

Third, we “call” the function twice. The first time, we used two arguments: pecans1 and chips2. The second time, we used two other arguments. In both cases, we assign a name to the outcomes. Those names are “todaysCookies” and “tomorrowsCookies.”

Fourth, we print out those outcomes within the larger context of a string. What we actually get in the Shell are the following  two sentences:

The yum factor for today’s cookies is 170
The yum factor for tomorrow’s cookies is 210

(In case you couldn’t tell, I’m a fan of cookies.)

Here’s how all the code looks in IDLE before we run it:

And here’s what prints out in your Shell:

PS: Sometimes I  think of functions as dogs and parameters as dog biscuits (you can see that I tend to be drawn to food-related metaphors). You “call” the dog and give her some nice parameters to work on. She gobbles them up, “passing” them right through the body, building strong bones and teeth, as the commercials say. Of course, if we take the metaphor too far, I guess it means that our functions ultimately pass stuff that we have to pick up with plastic bags in the park. Metaphors are dangerous that way.

PPS: If you’re looking for a more sensible tutorial on functions, here’s one you might try.

Featured image from Andrew6111. Wikimedia Commons.,_ready_to_munch.jpg

Um, What’s Your Function, Again?

On a first look at functions in Python

Everybody needs to find a place in this world, and that includes your computer code.  One of the best ways of making sure your code knows its proper place is by writing it in the form of a function.  A function is kind of like a lego block. You write it in such a way that it can connect up nicely with other functions and lines of code. Together, they build something cool.

These structured blocks of code are used to perform an action and return some type of value.  They’re modular, so you may be able to use them over and over. In fact, Python has lots of built-in functions, such as the “print” function, designed to make your life easier. You take its built-in blocks and snap them together with blocks of your own design.

It’s sort of like child’s play, but with more cursing.

You know a function when you see one because it starts with the keyword known as “def,” which stands for “define.” That is, you immediately define what your block of code does. It’s sort of like those nametags at business conferences: “Hi, I’m So-and-So, and Work at NameOfBiz as a NameOfOccupation.” Except functions somehow seem a lot less lame than nametags.

Function blocks start with def and then are followed by function’s name, parentheses and a colon (don’t forget the colon!). Like so:

def function_name():

But that’s not all, there’s more! A lot more, as you’ll see in the next post.

PS – If you’re the instant gratification type and want to learn more about functions right now, then here are some sites I recommend:

Featured image from GTurnbull925. Wikimedia Common.