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

Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »
Explore some of BBCs' most iconic s...
Despite your personal opinion on the BBC at a managerial level, it is undeniable that it has overseen some fantastic British shows in the past, and now thanks to a partnership with Roblox, players will be able to interact with some of these... | Read more »
Play Together teams up with Sanrio to br...
I was quite surprised to learn that the massive social network game Play Together had never collaborated with the globally popular Sanrio IP, it seems like the perfect team. Well, this glaring omission has now been rectified, as that instantly... | Read more »
Dark and Darker Mobile gets a new teaser...
Bluehole Studio and KRAFTON have released a new teaser trailer for their upcoming loot extravaganza Dark and Darker Mobile. Alongside this look into the underside of treasure hunting, we have received a few pieces of information about gameplay... | Read more »

Price Scanner via MacPrices.net

14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more
Sunday Sale: 13-inch M3 MacBook Air for $999,...
Several Apple retailers have the new 13″ MacBook Air with an M3 CPU in stock and on sale today for only $999 in Midnight. These are the lowest prices currently available for new 13″ M3 MacBook Airs... Read more
Multiple Apple retailers are offering 13-inch...
Several Apple retailers have 13″ MacBook Airs with M2 CPUs in stock and on sale this weekend starting at only $849 in Space Gray, Silver, Starlight, and Midnight colors. These are the lowest prices... Read more
Roundup of Verizon’s April Apple iPhone Promo...
Verizon is offering a number of iPhone deals for the month of April. Switch, and open a new of service, and you can qualify for a free iPhone 15 or heavy monthly discounts on other models: – 128GB... Read more
B&H has 16-inch MacBook Pros on sale for...
Apple 16″ MacBook Pros with M3 Pro and M3 Max CPUs are in stock and on sale today for $200-$300 off MSRP at B&H Photo. Their prices are among the lowest currently available for these models. B... Read more
Updated Mac Desktop Price Trackers
Our Apple award-winning Mac desktop price trackers are the best place to look for the lowest prices and latest sales on all the latest computers. Scan our price trackers for the latest information on... Read more
9th-generation iPads on sale for $80 off MSRP...
Best Buy has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80 off MSRP on their online store for a limited time. Prices start at only $249. Sale prices for online orders only, in-store prices... Read more
15-inch M3 MacBook Airs on sale for $100 off...
Best Buy has Apple 15″ MacBook Airs with M3 CPUs on sale for $100 off MSRP on their online store. Prices valid for online orders only, in-store prices may vary. Order online and choose free shipping... Read more

Jobs Board

Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Mar 22, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
Early Preschool Teacher - Glenda Drive/ *Appl...
Early Preschool Teacher - Glenda Drive/ Apple ValleyTeacher Share by Email Share on LinkedIn Share on Twitter Read more
Retail Assistant Manager- *Apple* Blossom Ma...
Retail Assistant Manager- APPLE BLOSSOM MALL Brand: Bath & Body Works Location: Winchester, VA, US Location Type: On-site Job ID: 04225 Job Area: Store: Management Read more
Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sonographer - *Apple* Hill Imaging Center -...
Sonographer - Apple Hill Imaging Center - Evenings Location: York Hospital, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now See Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.