How to Use a Class in Your Python Application

By John Paul Mueller

Most of the time, you use external classes when working with Python. It isn’t very often that a class exists within the confines of the application file because the application would become large and unmanageable. In addition, reusing the class code in another application would be difficult.

  1. Open a Python File window.

    You see an editor in which you can type the example code.

  2. Type the following code into the window — pressing Enter after each line:

    import MyClass
    SamsRecord = MyClass.MyClass()
    AmysRecord = MyClass.MyClass("Amy", 44)
    print(SamsRecord.GetAge())
    SamsRecord.SetAge(33)
    print(AmysRecord.GetName())
    AmysRecord.SetName("Aimee")
    print(SamsRecord)
    print(AmysRecord)

    The example code begins by importing the MyClass module. The module name is the name of the file used to store the external code, not the name of the class. A single module can contain multiple classes, so always think of the module as being the actual file that is used to hold one or more classes that you need to use with your application.

    After the module is imported, the application creates two MyClass objects. Notice that you use the module name first, followed by the class name. The first object, SamsRecord, uses the default settings. The second object, AmysRecord, relies on custom settings.

    Sam has become a year old. After the application verifies that the age does need to be updated, it updates Sam’s age.

    Somehow, HR spelled Aimee’s name wrong. It turns out that Amy is an incorrect spelling. Again, after the application verifies that the name is wrong, it makes a correction to AmysRecord. The final step is to print both records in their entirety.

  3. Choose Run→Run Module.

    The application displays a series of messages as it puts MyClass through its paces. At this point, you know all the essentials of creating great classes.

    image0.jpg