February 2006
Intermediate to advanced
648 pages
14h 53m
English
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 ...