Anatomy

A python class is defined using the ‘class’ keyword followed by the class name and a colon.  Instance variables and methods will be defined as shown below with proper indentation.

The constructor (__init__) and the destructor (__del__) are both optional.

class Dog:
    x = 0

   def __init__(self):
      print('Constructor executed')

   def __del__(self):
      print('Destructor executed')

   def increment(self):
    self.x = self.x + 1
    print('X is currently ', self.x)

One thing to note is that all class methods pass self as an argument.  When these methods get called, self is passed implicitly.

If we need arguments for the constructor or for any method, these would be listed after the self variable as shown next:

class Dog:
    x = 0
    name = "" 

    def __init__(self, z):
        self.name = z
        print(self.name, ' constructed') 

 

Utility Functions type and dir

If variable d is an instance of a class, the function call type(d) will provide us the class name for d and dir(d) will provide a list of all methods and instance variables for d.

 

Object Inheritance

The following code shows class definitions that include class inheritance

class Employee:
    firstName = ""
    lastName = ""

    def __init__(self, first, last):
        firstName = first
        lastName = last


class HourlyEmployee(Employee):
    hourlyRate = 0.00