Part 9b


Creating a Class in Python
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
#!/usr/bin/env python

import myclass as mc

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

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

main = main()

Place both files in a directory and make executable.

To run open up a terminal and cd to that directory then type ./ 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 myclass is imported into 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 with no argument.