TweetFollow Us on Twitter

Mac in the Shell: Learning Python on the Mac: Classes

Volume Number: 25
Issue Number: 05
Column Tag: Mac in the Shell

Mac in the Shell: Learning Python on the Mac: Classes

Building a Basic Class

by Edward Marczak

Introduction

Last month, we covered conceptually what classes are, why they're useful and when you may use them. This was all done with no (real) code. None of the nitty-gritty. That's where we're headed this month. So, without further ado, let's get into some Python code!

Modeling the Real World

Traditionally, defining a class is the mechanism that allows the code author to create a "factory" for churning out (instantiating) objects. Python is a little different in that everything is treated as an object whether you are aware of that fact or not. As we discussed last month, you use a class when you have a model in the real world that you'd like to follow. In his Road to Code column, Dave Dribin has been using shapes as objects. A single shape class can be used to model shapes from the real world: a square, a rectangle, etc. We're going to use a different example that's just as grounded in the real world: a bank account.

Before getting into the code, it's wise to plan out a class: what is it's structure? A class can hold instance variables and methods. An instance variable is simply a variable that is specific to a given class. Similarly, a method is a function that resides internal to a class, and can act on instance variables stored in a class.

What do we need to plan out our bank account class? Well, the account should have some method of identifying it - a name or number, perhaps. Since this is a small example, and we're not worried about name conflicts, and we don't want to treat people like a number, let's just go with name. That's one, actually two, instance variables: First Name and Last Name. The account will also have a balance, our third instance variable.

What actions do we need to take these variables? Focusing on the balance, we certainly need to deposit money. That's our first method! We'll also want to withdraw this money at some point, which will be our second method. Let's start modeling the class from here.

Bank Account Class

First things first: create a directory for this project. I'm using "Bank_Class", but you're free to call it what you wish. Inside that directory, I'm creating a file named "Bank_Class.py". Use vi, BBEdit or whichever plain text editor makes you most comfortable.

First thing is first; the magic shebang line:

#!/usr/bin/env python

As shown last month, classes always begin with the class keyword to define them:

class account:

and we said we need three instance variables: balance, first name and last name. We can define them here (but please read on as we're going to refine this!):

class account:
  balance = 0
  fname = ''
  lname = ''

From here, we can actually use this class:

acct = Account()  # Instantiate a new Account
print 'Account balance is', acct.balance
print 'Depositing $50'
acct.balance = acct.balance + 50
print 'Balance is now', acct.balance

Which yields the output:

Account balance is 0
Depositing $50
Balance is now 50

Now, just because we can doesn't mean that we should! This code will work, but it has a few holes. One large issue being that we don't have to assign a name to this account, and this is what we hoped to be our identifier. If there are actions we want to take, including assignment, every time we create an instance, we can define a constructor. A constructor is just another function (or, method). What makes it special is that it will run every time the class is instantiated. Defining a method named "__init__" creates a constructor (that's two underscores and the word 'init' followed by two underscores. Instead of the small tangled mess shown above, we can define the following:

class Account:
  def __init__(self, fn, ln):
    self.balance=0
    self.fname=fn
    self.lname=ln

Now when we instantiate the class, we can call it like this:

acct1 = Account('Bill', 'Smith')

This will create the account with a zero balance and assign the first name as "Bill" and the last name as "Smith". If we forget one or both parameters, the class will raise an error.

What's with the "self"?

Python requires that there be an additional first parameter to a class method. While you could technically name it anything you like, it's canonically called self. The Python runtime will automatically supply the value for this parameter at runtime. The self parameter is an object reference used to pass instance values to the method. While you can call it anything you like, all of the Python documentation uses "self," along with, well, every Python author that I know or have seen. So, stick with the convention of "self." It'll help you, or anyone that needs to look at your code in the future.

Additional Methods

Now that we can instantiate a new bank account, we'll want to act on it. We've already decided that we need at least two methods: deposit and withdraw. Add the methods to the class (remember the right indentation!):

class Account:
  def __init__(self, fn, ln):
    self.balance = 0
    self.fname = fn
    self.lname = ln
    
  def Deposit(self,amount):
    self.balance += amount
  
  def Withdraw(self, amount):
    self.balance -= amount

Now we can create a new account, deposit and withdraw money. (Note the use of the += and -= operators. This is simple shorthand for repeating the left-hand variable. x = x + 1 can become x += 1). Unlike the first version of this code shown above, we don't have to set the variables ourselves, but rather we use a method to do it for us:

acct = Account('Joan', 'Smith')    # Create new account
print "Acct1 Balance = ", acct1.balance
print "Depositing $50 to acct1"
acct1.Deposit(50)       # Note use of class method here
print "Acct1 Balance =", acct1.balance

Naturally, there are some holes with this. There are no sanity checks to see if there's any money in the account before we withdraw it, for one. That is an improvement left to the reader.

How is this better?

Well, the examples given thus far haven't done much to improve on traditional procedural programming. However, now that we have the structure in place, it's easy to go beyond that. Creating multiple accounts, for instance is as simple as an assignment:

acct1 = Account('Joan', 'Smith')
acct2 = account('Bob', 'Smith')

And we can perform discreet actions on each:

acct1.Deposit(50)
acct2.Deposit(1000)
print "Acct1 Balance =", acct1.balance
print "Acct2 Balance =", acct2.balance

You should be able to visualize a dictionary structure filled with accounts. Or, the ability to find a record in a database and loading the found record(s) into an Account class.

Conclusion

Between last month and this month - please ensure that you also understand the material presented last month, too! - you should have a pretty good idea what classes are, how they work, and how to start building your own. Next month, we'll get into some OS X-specific functionality of Python and build some useful classes.

Media of the month: http://www.facebook.com. Seriously. OK, pick any social network, but Facebook seems to be the biggest. And then go say hello to someone you miss.

Hope to see everyone at WWDC next month! See you in San Francisco!


Ed Marczak is the Executive Editor of MacTech Magazine. He lives in New York with his wife, two daughters and various pets. He has been involved with technology since Atari sucked him in, and has followed Apple since the Apple I days. He spends his days on the Mac team at Google, and free time with his family and/or playing music. Ed is the author of the Apple Training Series book, "Advanced System Administration v10.5," and has written for MacTech since 2004.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.