bembry.org
Home / Technology / Python / Notes

Lesson 17 Notes: More Class Stuff

  • Preview
    • Setting default values
    • Overloading
    • Class attributes
    • Driver functions
  • Setting Default Values
    • Functions can be set to have default values
    • These values are used only when a function call does not specify a value
      class Money:
      def __init__(self, amount = 0):
      self.amount = amount
  • Operator Overloading
    • Classes can redefine regular Python commands.
    • Changing how regular commands work in a class is called Operator Overloading.
    • To define operator overloading, you must use special names when defining the methods.
    • Overload definitions must return a value.
  • Operator Overloading Example
      class Weird:
          def __init__(self, num1 = 2):
              self.num1 = num1
          def __del__(self):
              print "%d Destroyed!" % self.num1
          def __repr__(self):
              return "Your number is %d" % self.num1
          def __add__(self, newnum):
              #Don't ever do this.
              return newnum*self.num1
  • Some Operator Overloading Methods
    • __add__ +
    • __sub__ -
    • __mul__ *
    • __div__ /
    • __pow__ **
    • __repr__ print
    • __len__ len(x)
    • __call__ x()
    • __init__ Creation
    • __del__ Destruction
  • Driver Function
    • A "driver function" is put at the end of a class to test it.
    • The function takes the form :
      if __name__ == '__main__':
          do stuff
    • When a class or module is called as the main program, it will run this code.
  • Class Attributes
    • Data that needs to be accessed by every instance (or object) of a class can be stored in class attributes
    • Values will be created outside of function definitions in main body of the class
    • Data will be changed or accessed within the function definitions (methods) us Classname.variablename notation.
  • Sample Class Attributes
      class Accounts:
         employees = []
         def __init__(self, name):
              self.name = name
              Accounts.employees.append(self.name)
         def __del__(self)
              Accounts.employees.remove(self.name)
    • Note that the employees list is always called by its full name (Accounts.employees)
    • To access the list outside of the class, use its full name (Accounts.employees)
  • Review
    • What is operator overloading?
    • How do you use class attributes?
    • Why would you set default values?
    • What is the purpose of a driver function?
    • How do you create a driver function?
Restricted access