10.3 Controlling Access to Attributes

Class Account’s methods validate their arguments to ensure that the balance is always valid—that is, always greater than or equal to 0.00. In the previous example, we used the attributes name and balance only to get the values of those attributes. It turns out that we also can use those attributes to modify their values. Consider the Account object in the following IPython session:

In [1]: from account import Account

In [2]: from decimal import Decimal

In [3]: account1 = Account('John Green', Decimal('50.00'))

In [4]: account1.balance
Out[4]: Decimal('50.00')

Initially, account1 contains a valid balance. Now, let’s set the balance attribute to an invalid negative value, then display the balance:

In [5]: account1.balance = Decimal('-1000.00')

In [6]: account1.balance
Out[6]: Decimal('-1000.00')

Snippet [6]’s output shows that account1’s balance is now negative. As you can see, unlike methods, data attributes cannot validate the values you assign to them.

Encapsulation

A class’s client code is any code that uses objects of the class. Most object-oriented programming languages enable you to encapsulate (or hide) an object’s data from the client code. Such data in these languages is said to be private data.

Leading Underscore (_) Naming Convention

Python does not have private data. Instead, you use naming conventions to design classes that encourage correct use. By convention, Python programmers know that any attribute name beginning with an underscore (_) is for a class’s internal use only. Client code should use the class’s methods and—as you’ll see in the next section—the class’s properties to interact with each object’s internal-use data attributes. Attributes whose identifiers do not begin with an underscore (_) are considered publicly accessible for use in client code. In the next section, we’ll define a Time class and use these naming conventions. However, even when we use these conventions, attributes are always accessible.

tick mark Self Check

  1. (True/False) Like most object-oriented programming languages, Python provides capabilities for encapsulating an object’s data attributes so client code cannot access the data directly.
    Answer: False. In Python, all data attributes are accessible. You use attribute naming conventions to indicate that attributes should not be accessed directly from client code.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.105.46