12.07.2015 Views

Is Python a

Is Python a

Is Python a

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

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

...class spam:...class ham:...class eggs:...# food.spam# food.ham# food.eggsThis holds true even if the module and class happen to have the same name. Forexample, given the following file, person.py:class person:...we need to go through the module to fetch the class as usual:import personx = person.person( )# Import module# Class within moduleAlthough this path may look redundant, it’s required: person.person refers to theperson class inside the person module. Saying just person gets the module, not theclass, unless the from statement is used:from person import personx = person( )# Get class from module# Use class nameLike any other variable, we can never see a class in a file without first importing andsomehow fetching it from its enclosing file. If this seems confusing, don’t use thesame name for a module and a class within it.Also, keep in mind that although classes and modules are both namespaces forattaching attributes, they correspond to very different source code structures: a modulereflects an entire file, but a class is a statement within a file. We’ll say more aboutsuch distinctions later in this part of the book.Classes Can Intercept <strong>Python</strong> OperatorsNow, let’s take a look at the third major difference between classes and modules:operator overloading. In simple terms, operator overloading lets objects coded withclasses intercept and respond to operations that work on built-in types: addition,slicing, printing, qualification, and so on. It’s mostly just an automatic dispatch mechanism:expressions and other built-in operations route control to implementations inclasses. Here, too, there is nothing similar in modules: modules can implement functioncalls, but not the behavior of expressions.Although we could implement all class behavior as method functions, operator overloadinglets objects be more tightly integrated with <strong>Python</strong>’s object model. Moreover,because operator overloading makes our own objects act like built-ins, it tends to472 | Chapter 23: Class Coding Basics

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

Saved successfully!

Ooh no, something went wrong!