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 ...

Get Python: Essential Reference, Third Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.