ClassesΒΆ

  • Classes allow you to define your own objects
  • Classes can contain both data values and functions
  • Classes can be derived (inherit) from other classes to extend features while avoiding duplication
class Bag(object):  # Derive from built-in base object.
  """
  This class represents a bag (i.e, container) of
  arbitrary stuff.
  """
  def __init__(self, stuff, *morestuff):  # Constructor method.
    self.contents = [stuff]
    for item in morestuff:
      self.contents.append(item)

  def __len__(self):
    """Returns the number of items in the bag."""
    return len(self.contents)

  def show(self):
    """Prints the contents of the bag."""
    print self.contents
  • Construct and use a Bag like this:
>>> b = Bag(1, 2.0, "three")
>>> len(b)
3
>>> b.show()
[1, 2.0, 'three']
>>> contents = b.contents  # No "private" data.
  • Classes are self-documenting via “doc strings”:
>>> help(b)
Help on Bag in module __main__ object:

class Bag(__builtin__.object)
 |  This class represents a bag (i.e, container) of arbitrary stuff.
 |
 |  Methods defined here:
 |
 |  __init__(self, stuff, *morestuff)
 |
 |  __len__(self)
 |      Returns number of items in the bag.
 |
 |  show(self)
 |      Prints the contents of the bag.
 |
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |
 |  __dict__
 |      dictionary for instance variables (if defined)
 |
 |  __weakref__
 |      list of weak references to the object (if defined)