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 attributes instead of instance attributes. Such methods usually keep track ofinformation that spans all instances (e.g., the number created), rather than providingbehavior for instances.In the prior chapter, we talked about unbound methods: when we fetch a methodfunction by qualifying a class (instead of an instance), we get an unbound methodobject. Even though they are defined with def statements, unbound method objectsare not simple functions; they cannot be called without an instance.For example, suppose we want to use class attributes to count how many instancesare generated from a class (as in the following file, spam.py). Remember, classattributes are shared by all instances, so we can store the counter in the class objectitself:class Spam:numInstances = 0def _ _init_ _(self):Spam.numInstances = Spam.numInstances + 1def printNumInstances( ):print "Number of instances created: ", Spam.numInstancesBut this won’t work—the printNumInstances method still expects an instance to bepassed in when called because the function is associated with a class (even thoughthere are no arguments in the def header):>>> from spam import *>>> a = Spam( )>>> b = Spam( )>>> c = Spam( )>>> Spam.printNumInstances( )Traceback (innermost last):File "", line 1, in ?TypeError: unbound method must be called with class instance 1st argumentThe problem here is that unbound instance methods aren’t exactly the same as simplefunctions. This is mostly a knowledge issue, but if you want to call functions thataccess class members without an instance, probably the most straightforward idea isto just make them simple functions, not class methods. This way, an instance isn’texpected in the call:def printNumInstances( ):print "Number of instances created: ", Spam.numInstancesclass Spam:numInstances = 0def _ _init_ _(self):Spam.numInstances = Spam.numInstances + 1>>> import spam>>> a = spam.Spam( )>>> b = spam.Spam( )>>> c = spam.Spam( )Static and Class Methods | 553

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

Saved successfully!

Ooh no, something went wrong!