Home > Articles > Programming > Python

  • Print
  • + Share This
Like this article? We recommend

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__ is used to initialize an object after it's created.

To use a class, write code such as the following:

s = Stack()      # Create a stack 
s.push("Dave")    # Push some things onto it
s.push(42)
s.push([3,4,5])
x = s.pop()      # x gets [3,4,5]
y = s.pop()      # y gets 42
del s         # Destroy s
  • + Share This
  • 🔖 Save To Your Account