Part 9b

Classes

Creating a Class in Python

myclass.py
class myclass:
  def __init__(self):
    # things you want to do when the class is created
    self.testit = 'this is a test'

  # defining a method with a default value for an argument
  def printit(self, info='No Argument Passed'):
    print info
glade9b.py
#!/usr/bin/env python

import myclass as mc

class main:
  def __init__(self):
    # create an instance of a class
    self.mc = mc.myclass()

    # use a method from the class
    print 'calling printif with an argument'
    self.mc.printit('This was passed to printit')
    print 'calling printit with no argument'
    self.mc.printit()

main = main()

Place both files in a directory and make main.py executable.

To run open up a terminal and cd to that directory then type ./glade9b.py to see it run.

This shows the basic structure of a class and importing a class and using it. While this is not hugely fasinating to run the basics of creating a class and using it is shown.

When we execute main.py myclass is imported into main.py as mc or it could be almost any name. I just choose mc to save typing. The main class is called by the last line main = main(). When the main class is ran it creates a instance of mc.myclass. Then we can access the methods in that class by using the instance.method names and passing any parameters needed by that method.

Notice that the info argument of the printit method has a default if no argument is passed the default is used. This is shown by the second call to self.mc.printif() with no argument.