Linux/Unix > Python Essential Reference, Second Edition > 1. A Tutorial Introduction > Classes | See All Titles

< BACK | Make Note | Bookmark | CONTINUE >

155117184014003188065099048180054212144238241179195140058238110137110165121169154060231060

### Classes

The `class` statement is used to define new types of objects and for object-oriented programming. For example, the following class defines a simple stack:

    class Stack:
            def _ _init_ _(self):              # Initialize the stack
                    self.stack = [ ]
            def push(self,object):
                    self.stack.append(object)
            def pop(self):
                    return self.stack.pop()
            def length(self):
                    return len(self.stack)

In the class definition, methods are defined using the `def` statement. The first argument in each method always refers to the object itself. By convention, `self` is the name used for this argument. All operations involving the attributes of an object must explicitly refer to the `self` variable. Methods with leading and trailing double underscores are special methods. For example, `_ _init_ _` is used to initialize an object after it’s created.

To use a class, write code such as the following:

    s = Stack()           # Create a stack
    s.push("Dave")        # Push some things onto it
    s.push(42)
    s.push([3,4,5])
    x = s.pop()           # x gets [3,4,5]
    y = s.pop()           # y gets 42
    del s                 # Destroy s

| Last updated on 3/28/2002 Python Essential Reference, Second Edition, © 2002 New Riders Publishing

< BACK | Make Note | Bookmark | CONTINUE >

© 2002, O'Reilly & Associates, Inc.