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.

spam.printNumInstances( )Number of instances created: 3>>> spam.Spam.numInstances3Because the class name is accessible to the simple function as a global variable, thisworks fine. Also, note that the name of the function becomes global, but only to thissingle module; it will not clash with names in other files of the program.We can also make this work by calling the function through an instance, as usual,although this can be inconvenient if making an instance changes the class data:class Spam:numInstances = 0def _ _init_ _(self):Spam.numInstances = Spam.numInstances + 1def printNumInstances(self):print "Number of instances created: ", Spam.numInstances>>> from spam import Spam>>> a, b, c = Spam(), Spam( ), Spam( )>>> a.printNumInstances( )Number of instances created: 3>>> b.printNumInstances( )Number of instances created: 3>>> Spam( ).printNumInstances( )Number of instances created: 4Prior to <strong>Python</strong> 2.2’s static method extension, some language theorists claimed thatthe availability of this technique meant that <strong>Python</strong> didn’t have class methods, onlyinstance methods. I suspect they really meant that <strong>Python</strong> classes don’t work thesame as classes in some other languages. What <strong>Python</strong> really has are bound andunbound method objects, with well-defined semantics; qualifying a class gets you anunbound method, which is a special kind of function. <strong>Python</strong> does have classattributes, but functions in classes expect an instance argument.Moreover, because <strong>Python</strong> already provides modules as a namespace-partitioningtool, there’s usually no need to package functions in classes unless they implementobject behavior. Simple functions within modules usually do most of what instancelessclass methods could. For example, in the first code sample in this section,printNumInstances is already associated with the class because it lives in the samemodule. The only lost functionality is that the function name has a broader scope—the entire module, rather than the class.Using Static and Class MethodsToday, there is another option for coding simple functions associated with a class. Asof <strong>Python</strong> 2.2, you can code classes with static and class methods, neither of whichrequires an instance argument to be passed in when they are invoked. To designate554 | Chapter 26: Advanced Class Topics

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

Saved successfully!

Ooh no, something went wrong!