CIS 111 Classes and objects

Objectives

  • Create a class
  • Create functions/methods within a class
  • Create an object from a class
  • Implement a constructor
  • Implement a destructor

Class overview

  • a class is created using the keyword: class
  • functions that are part of objects are usually called methods
  • class methods must have a first parameter: self
  • the self parameter is supplied automatically by Python when calling
  • a constructor is a method run at object instantiation to initialize the object
  • the constructor method for Python objects is called: __init__

Class and constructor example

class Employee: count = 0 # could make private using: __count def __init__(self, id="** No ID **", name=""): """Constructor""" self.id = id self.name = name Employee.count += 1 def die(self): """Destructor""" Employee.count -= 1 def talk(self): if (len(self.name) > 0): print('{} says, "Hello!"'.format(self.name)) else: print("Hi.") def __str__(self): if len(self.name) == 0: return "{0} ({1})".format("Unknown", self.id) else: return "{0} ({1})".format(self.name, self.id) @classmethod def getCount(cls): """Returns object count""" return cls.count emp = Employee() emp.talk() barney = Employee(name="Barnaby", id="715563") barney.talk() print("There are {0} employees".format(Employee.getCount())) print(emp) print(barney) emp.die() barney.die() print("Both employees let go. Now there are {0}.".format(Employee.getCount()))