Creating New Objects

0
209

Although IronPython has a wealth of built-in objects, you eventually need to create your own objects for an application of any complexity. If you’ve worked with other languages and scratched your head over some of the requirements for creating a class, you’ll find that IronPython is a welcome change. Creating and using custom classes in IronPython is amazingly easy. The following sections tell you how to create a basic class and then show how to use it.

Defining the IronPython Class

An IronPython class can have both attributes (properties) and methods, just as any class in any other language can have. However, IronPython classes have a few quirks as well. Listing 5-1 shows an example of a simple IronPython class.

Listin g 5-1: Defining a simple class

[code]

class MyGreetings:
# Greeting name variable.
Name = ‘Sammy’
# Provides a hello greeting.
def SayHello(self):
print ‘Hello there’, self.Name, ‘!’
# Provides a goodbye message.
def SayGoodbye(self):
print ‘See you later’, self.Name, ‘!’

[/code]

The class description starts out with the word class, as you might expect, and the name of the class. If you plan to inherit from another class, you enclose its name in parentheses behind the class name like this:

[code]

class MyGreetings(sys):

[/code]

In this case, the MyGreetings class would inherit from the sys class. A class definition ends with a colon, just like every other structure in IronPython. You use indentation, as normal, to signify the end of the class.

Attributes are simply variables that you declare as part of the class. As you can see, you normally define a default value for attributes. An attribute can be of any type.

Methods are simply a different kind of function in IronPython. You define them within the class as you might expect. A method uses def as the starting point, followed by the method name. Notice that both methods, SayHello() and SayGoodbye(), have an input variable named self. When you create an instance of a class, the interpreter automatically creates the self variable for that instance. The self variable contains all of the data associated with that instance, such as Name in this case.

As shown in the method code, you can use any of the data that self provides. In this case, the code accesses self.Name to obtain the name you assigned to the Name attribute (or the default, if you haven’t). If you were to try to access Name directly, the interpreter would display an error message.

Using Custom Objects in IronPython

At this point, you have a shiny new class named MyGreetings. Normally, you won’t place the class and the code that uses it in the same file, so the example places the test code in TestFirstClass.py. Consequently, the first thing the example does is import MyGreetings from FirstClass, as shown in Listing 5-2.

Listin g 5-2: Testing the simple class

[code]

from FirstClass import MyGreetings
# Create an instance of the class.
TestIt = MyGreetings()
# Set the Name attribute.
TestIt.Name = ‘George’
# Call the two methods.
TestIt.SayHello()
TestIt.SayGoodbye()
# Pause after the debug session.
raw_input(‘Press any key to continue…’)

[/code]

At this point, the code creates an instance of MyGreetings and places it in TestIt. Notice that the call to MyGreetings doesn’t require any data. If you want to request data from the caller during instantiation, you must provide an __init__() method in your class declaration. Otherwise, the interpreter provides a default declaration for you that creates the desired object.

The code changes the value of Name by assigning a new value to it. Notice that you assign the new value to TestIt.Name, just as you would in any other language.

Next, the code calls the two methods, SayHello() and SayGoodbye(). Notice that the method calls don’t require any input, and IronPython would complain if you tried to provide it. Remember that the interpreter provides self in the background. Figure 5-2 shows the output from this application.

Figure 5-2: The simple class outputs the expected information.
Figure 5-2: The simple class outputs the expected information.

Adding Documentation

It’s important to add documentation to your class as soon as possible — preferably while you’re typing the code. Many IronPython developers work in the interpreter to create applications faster and rely on the help() function or __doc__ attribute to understand what a method does with considerably less effort than finding the documentation.

Adding documentation to your class is straightforward. You simply add strings immediately after the class or method definition. A string that documents your class is called a docstring. IronPython doesn’t recognize docstrings that appear in places other than class and method declarations. For example, if you place a docstring after an attribute, it won’t appear when you use the help() function or __doc__ attribute. However, third-party tools often pick up these additional docstrings and place them in any documentation they output. Listing 5-3 shows the example class with docstrings in place.

Listin g 5-3: Adding documentation to a class

[code]

class MyGreetings:
“”“Contains a list of messages that you want to send to the user.
Make sure you assign a value to Name before using any of the
greetings so the message is customize for that user.”“”
# Greeting name variable.
Name = ‘Sammy’
“”“Provides the user’s name.”“”
# Provides a hello greeting.
def SayHello(self):
“”“Outputs an interesting greeting to the user.”“”
print ‘Hello there’, self.Name, ‘!’
# Provides a goodbye message.
def SayGoodbye(self):
“”“Outputs a goodbye message to the user.”“”
print ‘See you later’, self.Name, ‘!’

[/code]

Docstrings can consume one or more lines. The standard convention is to place docstrings within triple quotes as shown in the listing. You can find a number of other docstring conventions at http://www.python.org/dev/peps/pep-0257/.

After you create your docstrings, start the IronPython interpreter and load your class. You can try the docstrings out using either the help() function or __doc__ attribute. Figure 5-3 shows the docstring output for the example class.

Figure 5-3: Docstrings add greatly to the usability of your application.
Figure 5-3: Docstrings add greatly to the usability of your application.

Self-documenting your application is great, but some people will prefer some sort of HTML documentation. Don’t worry; you can get a tool to handle this requirement as well. PythonDoc (http:// effbot.org/zone/pythondoc.htm) provides the same type of functionality that JavaDoc does. It’s akin to generating the documentation you need when you compile your application in Visual Studio. PythonDoc locates all of the comments in your code and uses them to create HTML documentation that others can use when working with your classes.