Skip to Content
Python: Essential Reference, Third Edition
book

Python: Essential Reference, Third Edition

by David Beazley
February 2006
Intermediate to advanced content levelIntermediate to advanced
648 pages
14h 53m
English
Sams
Content preview from Python: Essential Reference, Third Edition

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 with push(), pop(), and length() operations:

class Stack(object):
        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 first line of the class definition, the statement class Stack(object) declares Stack to be an object. The use of parentheses is how Python specifies inheritance—in this case, Stack inherits from object, which is the root of all Python types. Inside the class definition, methods are defined using the def statement. The first argument ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python: Essential Reference

Python: Essential Reference

David M. Beazley

Publisher Resources

ISBN: 0672328623Purchase book