1. Home
  2. Computing & Technology
  3. Python

Beginning Python: Putting It All Together With Syntax

From , former About.com Guide

7 of 10

Classes - Part 2

A computer stack is a temporary abstract data structure which operates on the principle of 'last in first out' (more information on it may be found at http://en.wikipedia.org/wiki/Stack_data_structure). In this class definition, the first function is for the class itself. This is a required part of every class; it must have a function pertaining to itself. As the activities around a stack are essentially two, two functions are set up. The first pushes data on the stack. The second pops off the last piece of data. Finally, a very helpful piece of information to know is how many items are in the stack. For this, the class has a length function.

To initate a class, simply assign an instance to a variable name as shown in the first line below. One accesses the methods of the class by prefixing the name of the instance to the name of the method.

heap = Stack() # Create an instance of the class
heap.push('Belteshazar') # Push items on the instance heap of class Stack
heap.push(['Battle of Hastings', 1066])
heap.push('1945')
a = heap.pop() # Assigns '1945' to a
b = heap.pop() # Assigns '[Battle of Hastings, 1066]' to b
c = heap.pop() # Assigns 'Belteshazar' to c
del heap # Destroy the instance heap of class Stack

Explore Python
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. Python

©2009 About.com, a part of The New York Times Company.

All rights reserved.