Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Wednesday, September 10, 2014

Object Orientation


Here's the audio version of this blog post:



These are objects
What is an object?  In real life, a lot of things are objects.  Plants, bicycles, cars, pets, bananas, thoughts, really anything!  Even people could be considered objects (bear with me here).  The question "what is an object" raises some philosophical issues, but it is clear that objects play a large role in our daily lives.

Because objects are so pervasive in our perception of the world, we can say we experience life in an object-oriented way.  For example, take the sentence "I'm going to the store".  Here, "I" refers to the person object that is going to the store.  The store could be interpreted as a destination object, which implies that there is also an origin object.  The subject of our example may plan on driving his car object to the store, or riding a bike object.  At the store, a person can buy food objects.

This example again raises the question, What is an object?
Let's define some criteria for object-ness:

  • An object must have characteristics
    • Tangible characteristics:
      • Color, size, weight, location
    • Non-tangible characteristics:
      • Emotions, personality traits, powered on, powered off
  • An object must have actions
    • Things that it can do or things that can be done to it
      • Run, walk, eat, drive
      • Power on, power off
      • Paint (change color)
      • Grow
  • An object must be identifiable
    • It must be a distinct entity
      • I can have two pens of the same model, but I still have two different pens
Notice how we never specified that an object must physically exist.  Our criteria for an object could include thoughts, conversations or mathematical formulas.

Because objects are so omnipresent in life and the human experience, things we create will reflect this object-oriented way of thinking.  Humans can easily think of problems in terms of objects, so we created many software tools to describe and interact with objects.  Programs that simulate icebergs melting or control aircraft scheduling patterns can be developed in an object-oriented way.

Not how it is
So, this means when we write most programs, it is easiest to write them in an object-oriented way.  This results in minimal effort on the programmer's part.  Well designed object-oriented programs read more like a description of the real world than arcane source code.









Alright, let's see some code.

class Pig:
    #definition for Pig object
    def __init__(self, weight, age, name):
        #a pig has weight (lbs), age (years) and a name
        
        #assigning parameters to pig object
        self.weight = weight
        self.age = age
        self.name = name
    
    def oink(self):
        print "Oink!"
        
    def sayHello(self):
        print "Hello, my name is " + self.name + "."

#make a new pig named Spider pig that weighs 40 lbs.
#and is 3 years old
SpiderPig = Pig(40, 3, "Spider Pig")

#make spider pig introduce himself
SpiderPig.sayHello()

#make spider pig oink
SpiderPig.oink()

Here's a link to an editable and runnable version of that example.

The programming language I used to write that example is called Python (named after Monty Python's Flying Circus).  If you want a more in-depth introduction, check out my blog posts Python Intro and Python Intro Part Deux.  I also wrote an introduction to Java, another object oriented programming language.

Monday, September 8, 2014

Argument Unpacking in Python (holy balls!)

Hey y'all, I'm here to teach you about Argument Unpacking.  Please, try to remain in your seats.
Woah that guy just got Argument Unpacking













So I had to do some screen scraping (follow that link).  Yuck, right?  Except no, I get some weird sick pleasure out of screen scraping (I volunteer to do it).

(Skip this if you know what screen scraping is)
So in short screen scraping is when you translate a hard-to-traverse website into a nice data structure like json.

Anyways, I was writing a screen scraper for the paint mixer.  I made classes for my data templates (yay go me).  At first, I thought it would be easy to just iterate through the table cells using BeautifulSoup (a very cool and excellent Python html parser).  That was not good.


for cell in cells:
   if cellNumber == 0:
    try:
     cardNumber = cell.contents[0]
    except IndexError:
     cardNumber = None
   elif cellNumber == 1:
    try:
     firstName = cell.contents[0]
    except IndexError:
     firstName = None
   elif cellNumber == 2:
    try:
     lastName = cell.contents[0]
    except IndexError:
     lastName = None
   elif cellNumber == 3:
    try:
     email = cell.contents[0]
    except IndexError:
     email = None
   elif cellNumber == 4:
    try:
     balance = cell.contents[0]
    except IndexError:
     balance = None

^^^ Holy Mother that is bad

I knew Python just had to have a better alternative to this (the word pythonic is a thing, talk about a language dating itself), so I did me some googling and came upon a glorious find: argument unpacking.
This is going to be you in a few sentences











The Astute Reader (tm):  Wow, that traversal Max was talking about seemed really array-like!  I bet there's an easier way to do that!
Me:  Gee thanks captain obvious!  You don't think I was lamenting that with every line I wrote?  I knew I was so close!
The Astute Reader (tm):  Ok, that was an obvious lead-in to Argument Unpacking.  Let's have it, then.

Ok, here it is...drumroll please.

I have a method that takes 6 parameters:

def method_with_lots_of_freaking_parameters(x1, y1, x2, y2, x3, y3):
 print "Haha I'm not even going to use those arguments!"

And I have a list with those parameters stored just itching to be passed to that method
superswaglist = [5, 1, 3, 6, 6, 6]  #wow this is super contrived huh?

Without Argument Unpacking, this is how you'd have to call that method
method_with_lots_of_freaking_parameters(superswaglist[0], superswaglist[1], superswaglist[2], superswaglist[3], superswaglist[4], superswaglist[5])  #puke

But with this blessed tool (In the Name of Python We Pray), we simply call

method_with_lots_of_freaking_parameters(*superswaglist)  #wow such ease
I couldn't agree more
This tool condensed 56 lines of code into one for my screen scraper tool.  Be excited.

PS If you want a tutorial on screen scraping let me know in the comments!

Friday, September 6, 2013

Python Intro

repl.it
So you've finally decided you want to learn to program.  Or maybe you know how to program but you want to learn Python.  In either case, this tutorial is for you!  This is for complete Python beginners.



Python logo
Before you can write and use any Python, you need to find an application that will run your code.  For expediency's sake I will skip over installing and running Python natively; we'll use repl.it (a free online interpreter) instead.  This guide is written for Python 2, so if you have Python 3 installed just use repl.it.  Navigate to repl.it, click the languages button (the leftmost button in the top right corner of the screen) and set it to Python, then click anywhere in the area of the screen on the right side with the blue background.  Now let's write some code!

To start off, type:
print "Hello world!"
and press Enter.

You should see this:






You just added to a 41 year old tradition and wrote your first Python program!  Well done.
The "Hello World" example illustrates the usage of Python's print statement.  To print a string (a collection of zero or more characters delineated by quotation marks, like "Yolo swag", "hello", "5.24" or "D"), type print followed by the phrase you wish to print enclosed in quotation marks.  Here are some more examples of print:
print "Size matters not - Yoda"
print 42
print "It's a great day to be alive!"
Play around with the interpreter.  See what works and what doesn't.  Try printing numbers, fractions or punctuation.  Try using single quotation marks on strings.

Python (like every other good programming language) lets us save values to variables for later use.  Think of a variable like a box.  A box can hold books, toys or video games and a variable can hold strings, integers and doubles (plus much more).  To save a value to a variable, type a variable name followed by an equals sign (=) followed by the value you wish to save.  For example:
x = 42
Now the variable x holds the value 42.  We can verify this by printing x:
x = 42
print x
You can print variables in much the same way that you can print numbers or strings.  Try the above example, then play around with the interpreter.  Here are some more examples to help you get the hang of the syntax:
the_answer = 42
price = 1.95
userName = "macsj200"
x = price
elephant_name = "Dumbo"
Try setting x to a different string, or a number.  Try creating other variables.  Try setting x equal to another variable.  Try printing variables before you create them.  Use the print statement to see the results of your actions.

Python variables must start with a letter and be only one word, but other than that name then whatever you want.  It is a good idea to get into the habit of giving your variables meaningful names, like speed or priceOfIitem or number_of_cans instead of x or zs.  Food for thought: what is the difference between print x and print "x"?

Click here to go to Part 2

List Comprehensions in Python

Python logo
Why hello there fellow netizens!  It's good to finally have been forced to start a blog because I certainly have a lot to share with the world.  This post will serve to be a short expose on a wonderful feature of the Python programming language (named after the t.v. show "Monty Python's Flying Circus") called List Comprehensions.  It's essentially a severely under-appreciated extension of Python's famous lists.  Before we jump in to the rest of the post, I suggest you familiarize yourself with Python lists using my demo on repl.it or the official Python docs if you don't already know how they work or need a refresher.


Ok, now let's start comprehending some lists! Say we have a list, x_list, that contains [1, 2, 3] and we want y_list to contain the value of each element of x_list squared.  That is to say, we want y list to contain [1, 4, 9].  Python makes this a very easy task indeed.

We could do it the schmuck way with a for loop:
x_list = [1, 2, 3]
y_list = []
for n in x_list:
    y_list.append(n * n)
print y_list

But, of course, Python supplies us mortals with List Comprehensions (a delightfully abbreviated syntax):
x_list = [1, 2, 3]
y_list = [n * n for n in x_list]
print y_list

Both versions print [1, 4, 9], but the List Comprehensions version is indisputably more elegant.  One thing I fail to understand is why the developers decided to make "Comprehensions" plural, but such is life.