O'Reilly logo

Python: Essential Reference, Third Edition by David Beazley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required