Understanding Object Encapsulation


You first learned about the concept of encapsulation with functions in the "Understanding Encapsulation" section of in Chapter 6. You saw that functions are encapsulated and hide the details of their inner workings from the part of your program that calls it (called the client of the function). You learned that the client of a well-defined function communicates with the function only through its parameters and return values. In general, objects should be treated the same way. Clients should communicate with objects through method parameters and return values. In general, client code should avoid directly altering the value of an object's attribute.

As always, a concrete example helps. Say, for example, that you had a Checking_Account object with a balance attribute. Let's say your program needs to handle withdrawals from accounts, where a withdrawal decreases an object's balance attribute by some amount. To make a withdrawal, client code could simply subtract a number from the value of balance. This direct access is easy for the client, but can cause problems. The client code may subtract a number so that balance becomes negative, which might be considered unacceptable (especially by the bank). It's much better to have a method called withdraw() that allows a client to request a withdrawal by passing an amount to the method. Then, the object itself can handle the request. If the amount is too large, the object can deal with it, possibly rejecting the transaction. The object keeps itself safe by providing indirect access to its attributes through methods.




Python Programming for the Absolute Beginner
Python Programming for the Absolute Beginner, 3rd Edition
ISBN: 1435455002
EAN: 2147483647
Year: 2003
Pages: 194

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net