PEP 245: Python interfaces
Raymond Hettinger
othello at javanet.com
Sat Mar 24 01:48:57 EST 2001
Michel Pelletier wrote:
>
> > d) What is also missing from Python is
> > an "auto-delegation". An analysis
> > of how this fits in or doesn't fit
> > in would be helpful.
>
> What is that? I've neve heard of auto-delegation.
>
class AutoDelegate:
'Mixin class autodelegates to objects listed in "delegationVars"'
def __getattr__( self, key ):
if not self.__dict__.has_key('delegationVars'): delegationVars=[]
for str in self.delegationVars: # if deleVars not defined, skip
try:
return getattr( self.__dict__[str], key )
except KeyError:
pass
except AttributeError:
pass
raise AttributeError, key
class Movie( AutoDelegate ): # installs the AutoDelegate mixin
delegationVars = ['priceCode'] # list of references to delegates
def __init__( self, title ):
self.priceCode = RegularPrice()
self.title = title
def changeCode( self, aPriceObj ):
self.priceCode = aPriceObj
##def getPrice( self, qty ): # Delegated method no longer needed
## self.priceCode.getPrice(qty)
class RegularPrice:
def getPrice( self, qty ):
return 10*qty
class DiscountedPrice:
def getPrice( self, qty ):
return 10 + 9 * (qty-1)
a = Movie('Rambo')
b = Movie('Aliens')
b.changeCode( DiscountedPrice() )
print a.getPrice(10), b.getPrice(12) # these calls automatically forwarded
More information about the Python-list
mailing list