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

Get Python Essential Reference, Second 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.