Welcome to MSDN Blogs Sign in | Join | Help

Learning IronPython #9: Classes

I can declare a class in IronPython as follows:

# File name: MySimpleMathClass.py
# Instantiate an instance of this class by calling the following:
#     import MySimpleMathClass
#     someObjectVariable = MySimpleMathClass.MySimpleMath()
# or similar.
class MySimpleMath:
    # You must define an __init__ method (similar to a constructor).
    # The first argument must be to self (the class instance).
    def __init__(self):
        # The pass keyword is a do-nothing statement
        # (similar to an empty constructor).
        pass
    # The first argument to all class methods must
    #
be to self (the class instance).
    # Invoke class methods by calling the following:
    #     someObjectVariable.add(10, 5)
    # or similar.
    def add(self, a, b):
        return a + b
    def subtract(self, a, b):
        return a - b
    def multiply(self, a, b):
        return a * b
    def divide(self, a, b):
        return a / b

I can then create an instance of that class and use its methods from the console as follows:

>>> import MySimpleMathClass
>>> MySimpleMathClassInstance = MySimpleMathClass.MySimpleMath()
>>> print MySimpleMathClassInstance.add(10,5)
15
>>> print MySimpleMathClassInstance.subtract(10,5)
5
>>> print MySimpleMathClassInstance.multiply(10,5)
50
>>> print MySimpleMathClassInstance.divide(10,5)
2

-- Paul

------------------------------------
This posting is provided "AS IS" with no warranties, and confers no rights.

Published Thursday, June 01, 2006 5:54 AM by Paul Cornell [MSFT]
Filed under:

Comments

No Comments
Anonymous comments are disabled
 
Page view tracker