When we subclass a built-in type, the result is a new-style class that can take advantage of the new class features introduced in Python 2.2. However, we will obviously want to define our own classes and take advantage of the added features. This can be done by simply subclassing object: >>> class NewStyle ( object ): >>> type ( NewStyle ) With that done, let's take a look at some of the new features that can be used by new-style classes, starting with properties. Properties are used in a way that is similar to the way regular attributes are used. However, there is one special difference between properties and regular attributes. Take a look at this class, which represents a hurricane: >>> class Hurricane ( object ): We can either pass the name and category when creating the Hurricane instance, or we can later set them with an attribute: >>> hugo = Hurricane ( 'Hugo', 4 ) So far, everything is fine. We have Hurricane Hugo at Category Four, and we have Hurricane Ophelia at Category One. However, consider the following example: >>> andrew = Hurricane() Here, we have a bit of a problem. Although Hurricane Andrew caused billions of dollars worth of damage, there is no “Category Six” for hurricanes. We're left with fixing this problem in our class. Sure, we could always require the user to pass the category when creating a Hurricane instance, but what's to stop them from changing it to whatever number they would like later on? >>> charley = Hurricane ( 'Charlie', 4 ) >>> charley.category 4 >>> charley.category = 7 >>> charley.category 7 There is a simple solution to our problem: properties. Properties allow us to control attributes, which is what we need to do to solve our problem. To create a property, we need to define two methods. One method will be responsible for obtaining the value of the property, and the other will be responsible for setting the value of the property. These method should manipulate an internal value, since the value and the property are two different things and obviously cannot share the same name. Here's our modified Hurricane class: >>> class Hurricane ( object ): Now let's try to set unrealistic category values: >>> camille = Hurricane ( 'Camille', 8 ) >>> camille.category 5 >>> danny = Hurricane() >>> danny.name = 'Danny' >>> danny.category = 0 >>> danny.category 1 If we wanted to, we could make the name of the hurricane an attribute, too. We could prefix the name of the hurricane with “Hurricane” when the property's value was requested: >>> class Hurricane ( object ): Here's our latest class in action: >>> georges = Hurricane ( 'Georges', 4 ) >>> georges.name 'Hurricane Georges' Properties are powerful tools, and they add a new level of intelligence to classes, allowing them to format outgoing data and change unrealistic incoming data. Again, however, properties can only be used in new-style classes.
blog comments powered by Disqus |
|
|
|
|
|
|
|