12.07.2015 Views

Is Python a

Is Python a

Is Python a

SHOW MORE
SHOW LESS
  • No tags were found...

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

x = limiter( )>>> x.age # Must assign before useAttributeError: age>>> x.age = 40>>> x.age40>>> x.ape = 1000 # Illegal: not in slotsAttributeError: 'limiter' object has no attribute 'ape'This feature was envisioned as a way to catch “typo” errors (assignments to illegalattribute names not in _ _slots_ _ are detected), and as an optimization mechanism(slot attributes may be stored in a tuple instead of a dictionary for quicker lookup).Slots are something of a break with <strong>Python</strong>’s dynamic nature, which dictates that anyname may be created by assignment. They also have additional constraints andimplications that are far too complex for us to discuss here. For example, someinstances with slots may not have a _ _dict_ _ attribute dictionary, which can makesome of the metaprograms we’ve coded in this book more complex; tools that genericallylist attributes, for instance, may have to inspect two sources instead of one. Seethe <strong>Python</strong> 2.2 release documents and <strong>Python</strong>’s standard manual set for more details.Class propertiesA mechanism known as properties provides another way for new-style classes to defineautomatically called methods for access or assignment to instance attributes. Thisfeature is an alternative to many current uses of the _ _getattr_ _ and _ _setattr_ _overloading methods we studied in Chapter 24. Properties have a similar effect tothese two methods, but they incur an extra method call only for accesses to namesthat require dynamic computation. Properties (and slots) are based on a new notion ofattribute descriptors, which is too advanced for us to cover here.In short, properties are a type of object assigned to class attribute names. They aregenerated by calling a property built-in with three methods (handlers for get, set, anddelete operations), as well as a docstring; if any argument is passed as None or omitted,that operation is not supported. Properties are typically assigned at the top levelof a class statement [e.g., name = property(...)]. When thus assigned, accesses to theclass attribute itself (e.g., obj.name) are automatically routed to one of the accessormethods passed into the property. For example, the _ _getattr_ _ method allowsclasses to intercept undefined attribute references:>>> class classic:... def _ _getattr_ _(self, name):... if name == 'age':... return 40... else:... raise AttributeError...550 | Chapter 26: Advanced Class Topics

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!