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.

A better alternative would be to restructure the code such that the class Spam isdefined at the top level of the module by virtue of its nesting level, rather than usingglobal declarations. The nested method function and the top-level generate will thenfind Spam in their global scopes:def generate( ):return Spam( )class Spam:count = 1def method(self):print Spam.count# Define at top level of module# Works: in global (enclosing module)generate( ).method( )In fact, this approach is recommended for all <strong>Python</strong> releases—code tends to be simplerin general if you avoid nesting classes and functions.If you want to get complicated and tricky, you can also get rid of the Spam referencein method altogether by using the special _ _class_ _ attribute, which returns aninstance’s class object:def generate( ):class Spam:count = 1def method(self):print self._ _class_ _.countreturn Spam( )generate( ).method( )“Overwrapping-itis”# Works: qualify to get classWhen used well, the code reuse features of OOP make it excel at cutting developmenttime. Sometimes, though, OOP’s abstraction potential can be abused to thepoint of making code difficult to understand. If classes are layered too deeply, codecan become obscure; you may have to search through many classes to discover whatan operation does.For example, I once worked in a C++ shop with thousands of classes (somemachine-generated), and up to 15 levels of inheritance. Deciphering method calls insuch a complex system was often a monumental task: multiple classes had to be consultedfor even the most basic of operations. In fact, the logic of the system was sodeeply wrapped that understanding a piece of code in some cases required days ofwading through related files.The most general rule of thumb of <strong>Python</strong> programming applies here, too: don’tmake things complicated unless they truly must be. Wrapping your code in multiplelayers of classes to the point of incomprehensibility is always a bad idea. Abstractionis the basis of polymorphism and encapsulation, and it can be a very effective toolClass Gotchas | 563

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

Saved successfully!

Ooh no, something went wrong!