|
|
||||||||||||||||||
|
|
||||||||||||||||||
![]() |
![]() |
Issue 2 - Revision 1 / Published in 2002
|
|||
POOPy: Introduction to Objects in Python Programming with Object Orientation in Python - - - - - - - - - - - - Greg Lindstrom | Originally published in Py Issue 2 Objects, in theory, are “things,” which are constructed in a manner hiding the inner workings, offering the user a simple interface to accomplish their tasks. Consider, for a moment, the telephone. It has (at least) a 10-digit keypad, a handset, and a ringer of some type. The user simply picks up the handset, dials a number, and can communicate with virtually any other telephone in the world. The user is not concerned with how the telephone works, and the phone company is able to modify things behind the scenes as long as the interface remains unchanged. The telephone is a real world “object.” In the coding world, an object is a way to group data (“members”) and the functions (“methods”) used to operate on the data in one place, allowing the object to be manipulated as a single entity. Ideally, the object will offer the user a simple, intuitive interface hiding any complexities such as computations or network communications, and allow us to make changes “behind the scenes” without concerning the user. Objects allow you to reuse your code -- really! -- by allowing you to connect and combine existing objects into bigger and better objects (“inheritance”). They are also a natural way to design and implement graphical user interfaces. Our friends in academia have various other requirements to define objects and object-oriented design, many of which Python supports and some it does not. The religious wars over what is and what isn’t considered object-oriented code makes the Perl vs. Python debate look like a childhood spat, and we will not be getting involved in it here.
For our first object, we will construct a door with one characteristic; it is either “opened”, or “closed” (thus, it has two “states”). Though this is but a few lines, I regularly use objects that contain thousands of lines of code. Here is the code to define our class, which we save to the file 1. class Door: 2. def __init__(self): 3. self.is_open = 0 4. 5. def Open(self): 6. self.is_open = 1 7. 8. def Close(self): 9. self.is_open = 0 10. 11. def State(self): 12. if self.is_open: return 'Opened' 13. else: return 'Closed' 14. 15. ### Unit Test Code ############################# 16. if __name__ == '__main__': 17. # create (instantiate) a door object 18. myDoor = Door() 19. print 'Door created with initial state:', myDoor.State() 20. 21. # open the door 22. myDoor.Open() 23. print 'The door is now', myDoor.State()
The Python keyword
Line 2:
Line 5:
Line 8:
Line 11:
All of our methods are defined with exactly one argument, namely You are undoubtedly concerned with the lack of documentation, hard coded values for “Opened” and “Closed” and the absence of features for our door (for example, should it have a lock? What about a description? And location? Does it have a window? It is loose pinned?). All in good time, gentle reader.
Line 16 shows a feature of Python, and a common method to unit test objects. If we save this file and execute it, the internal name will be We save the file as door.py and execute it (on Windows) with the command: C:\python door.py If you are using a tool such as PythonWin or IDLE, you can run the script from within the tool and the print lines will appear in the “interactive” window. Since we are running this as a standalone object, the unit test code is executed and we get the following lines written to the screen: C:\python door.py Creating a door object... Initial state is: Closed! Opening the door... Now the door is: Open! The method __init__() is automatically called when the object is created in line 18. In our case, this sets the state of the door to zero (“Closed”). Some folks may want to call this method the constructor and you may do that, too, if you like. I will not. For more information about __init()__ and much more, see the Python Language Reference (http://www.python.org/doc). We print the state of the door in line 19 by invoking the method State() on the object (myDoor). This is how all methods relating to the object will be called. Notice that even though the definition of the State() method has 1 argument (self, in line 11), Python automatically adds it, so we make the call in line 19 with no arguments. The door is opened in line 22, and we verify the state in line 23. Congratulations! You are now an object-oriented programmer, almost. Before you go demand a raise, though, we should look at a few more topics in future columns. Your assignment is to add a lock to the door class. We could define a new object, namely Deadbolt, and then add it to our Door (and Deadbolt could have a Tumbler object, which could have multiple Pin objects...), but let's keep things simple. Add a state variable to indicate if the door is locked or unlocked and make sure you set the initial value (you may decide if the door is initially locked or unlocked). Will adding a lock effect the Open() and Close() methods? Finally, add code to the unit test to verify your object behaves, as you would expect. Next time we will briefly look at how I implemented the lock (YMMV). We will also take a look at arguments for our methods, and start our documentation. We will then use our door class to create a “Structure” object (structure as in a house, not as in the things you studied in data structures) using different types of inheritance, and then we will build various types of houses, buildings, and skyscrapers. This particular article is Copyright © 2002 Greg Lindstrom. All Rights Reserved.
|
||||||||||
|
Py is committed to bringing you great Python Articles. | ||||||||||
![]() |
Reproduction of material from any of PyZine's pages without prior written permission is strictly prohibited. Copyright 2003 - 2005 PyZine |
|