Saturday 9 April 2016

Classes 2: __init__(self)

The code from Classes: Part 1 is just a simple introduction to classes. While the code does work, it could be more flexible and better defined. For example it would be more efficient if we could add the individual specifications for both Bob and Sue's bikes when the object instances are created. To do this we use the __init__(self) method to initialise the object instance with the correct values for each attribute.

We can see how this works with the following code.

#!/usr/bin/env python3

__project__= "Python Classes: The Bicycle Example"
__author__ = "Kevin Lynch"
__version__ = "$Revision: 2 $"
__date__ = "$Date: 2015/11/21 21:19:00 $"
__copyright__ = "Copyright (c) 2015 Kevin Lynch"
__license__ = "GPLv3"

class bicycle: # Defines the bicycle class.
        # Initialise bicycle with custom attributes.
        def __init__(self,frame,wheels):
                self.frameSet = frame
                self.wheelSet = wheels

# Global variables. Both reference the bicycle class.
bobsBike = bicycle("carbon","carbon")
suesBike = bicycle("steel","alloy")

print("Bob's Bike:\nFrame Set: " + bobsBike.frameSet + "\nWheel Set: " + bobsBike.wheelSet)
print("\n\nSue's Bike:\nFrame Set: " + suesBike.frameSet + "\nWheel Set: " + suesBike.wheelSet)

# We can still change things as before.
suesBike.frameSet = "plastic"

print("\n\nSue's Bike:\nFrame Set: " + suesBike.frameSet + "\nWheel Set: " + suesBike.wheelSet)

For such a small program __init__(self) may seem redundant. However getting to grips with this basic concept will make working with objects and classes much easier in larger programs.

No comments:

Post a Comment