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.

such methods, classes call the built-in functions staticmethod and classmethod, ashinted in the earlier discussion of new-style classes. For example:class Multi:def imeth(self, x):print self, xdef smeth(x):print xdef cmeth(cls, x):print cls, xsmeth = staticmethod(smeth)cmeth = classmethod(cmeth)# Normal instance method# Static: no instance passed# Class: gets class, not instance# Make smeth a static method# Make cmeth a class method.Notice how the last two assignments in this code simply reassign the method namessmeth and cmeth. Attributes are created and changed by any assignment in a classstatement, so these final assignments overwrite the assignments made earlier by thedefs.Technically, <strong>Python</strong> now supports three kinds of class-related methods: instance,static, and class. Instance methods are the normal (and default) case that we’ve seenin this book. You must always call an instance method with an instance object.When you call it through an instance, <strong>Python</strong> passes the instance to the first (leftmost)argument automatically; when you call it through a class, you pass along theinstance manually:>>> obj = Multi( ) # Make an instance>>> obj.imeth(1) # Normal call, through instance 1>>> Multi.imeth(obj, 2) # Normal call, through class 2By contrast, static methods are called without an instance argument; their names arelocal to the scopes of the classes in which they are defined, and may be looked up byinheritance. Mostly, they work like simple functions that happen to be coded insidea class:>>> Multi.smeth(3) # Static call, through class3>>> obj.smeth(4) # Static call, through instance4Class methods are similar, but <strong>Python</strong> automatically passes the class (not an instance)in to a class method’s first (leftmost) argument:>>> Multi.cmeth(5) # Class call, through class_ _main_ _.Multi 5>>> obj.cmeth(6) # Class call, through instance_ _main_ _.Multi 6Static and class methods are new and advanced features of the language, with highlyspecialized roles that we don’t have space to document fully here. Static methods arecommonly used in conjunction with class attributes to manage information thatStatic and Class Methods | 555

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

Saved successfully!

Ooh no, something went wrong!