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.

the instance’s memory address by calling the built-in id function, which returns anyobject’s address (by definition, a unique object identifier):############################################ Lister can be mixed into any class to# provide a formatted print of instances# via inheritance of _ _repr_ _ coded here;# self is the instance of the lowest class.###########################################class Lister:def _ _repr_ _(self):return ("" %(self.__class__._ _name_ _, # My class's nameid(self),# My addressself.attrnames( )) )# name=value listdef attrnames(self):result = ''for attr in self._ _dict_ _.keys( ):# Instance namespace dictif attr[:2] == '_ _':result = result + "\tname %s=\n" % attrelse:result = result + "\tname %s=%s\n" % (attr, self._ _dict_ _ [attr])return resultInstances derived from this class display their attributes automatically when printed,giving a bit more information than a simple address:>>> from mytools import Lister>>> class Spam(Lister):... def _ _init_ _(self):... self.data1 = 'food'...>>> x = Spam( )>>> xThe Lister class is useful for any classes you write—even classes that already have asuperclass. This is where multiple inheritance comes in handy: by adding Lister tothe list of superclasses in a class header (mixing it in), you get its _ _repr_ _ for freewhile still inheriting from the existing superclass. The file testmixin.py demonstrates:from mytools import Lister# Get tool classclass Super:def __init__(self):self.data1 = "spam"class Sub(Super, Lister):def _ _init_ _(self):Super._ _init_ _(self)self.data2 = "eggs"self.data3 = 42# superclass _ _init_ _# Mix in a _ _repr_ _# Lister has access to self# More instance attrs530 | Chapter 25: Designing with Classes

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

Saved successfully!

Ooh no, something went wrong!