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.

Class GotchasMost class issues can usually be boiled down to namespace issues (which makessense, given that classes are just namespaces with a few extra tricks). Some of thetopics we’ll cover in this section are more like case studies of advanced class usagethan problems, and one or two of these gotchas have been eased by recent <strong>Python</strong>releases.Changing Class Attributes Can Have Side EffectsTheoretically speaking, classes (and class instances) are mutable objects. Like built-inlists and dictionaries, they can be changed in-place by assigning to their attributes—and, as with lists and dictionaries, this means that changing a class or instance objectmay impact multiple references to it.That’s usually what we want (and is how objects change their state in general), butthis becomes especially critical to know when changing class attributes. Because allinstances generated from a class share the class’ namespace, any changes at the classlevel are reflected in all instances unless they have their own versions of the changedclass attributes.Because classes, modules, and instances are all just objects with attributenamespaces, you can normally change their attributes at runtime by assignments.Consider the following class. Inside the class body, the assignment to the name agenerates an attribute X.a, which lives in the class object at runtime, and will beinherited by all of X’s instances:>>> class X:... a = 1 # Class attribute...>>> I = X( )>>> I.a # Inherited by instance1>>> X.a1So far, so good—this is the normal case. But notice what happens when we changethe class attribute dynamically outside the class statement: it also changes theattribute in every object that inherits from the class. Moreover, new instances createdfrom the class during this session or program run get the dynamically set value,regardless of what the class’ source code says:>>> X.a = 2 # May change more than X>>> I.a # I changes too2>>> J = X( ) # J inherits from X's runtime values>>> J.a # (but assigning to J.a changes a in J, not X or I)2Class Gotchas | 559

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

Saved successfully!

Ooh no, something went wrong!