[Tutor] making onthefly attributes persistent

Alan Gauld alan.gauld at btinternet.com
Mon Dec 13 20:44:37 CET 2010


"Jojo Mwebaze" <jojo.mwebaze at gmail.com> wrote

> Assuming i have a class bank as below .
>
> class bank(object):
>   def __init__(self, bal=0):
>       self.bal = bal
>   def deposit(self, amount):
>       self.bal+=amount
>       print self.bal
>
> I define a method debit - which i add to the class onthefly
>
> bank.debit = debit
>
> #I can also add an attribute owner
>
> myaccount.owner = 'jojo'

> My problem is how to make the added attributes, 'owner' and 'debit'
> persistent automatically

If that's your only problem with this approach congratulations!
How does your orther code know when/if these dynamic
operations/data exist so as to use them? If they just assume
they exist then why not just add them in the definition. Even as 
nulls?

While Python allows you to dynamically add features to classes/objects
its not something I would recommend unless you have a really good
reason - not least because you bring upon yourself all sorts of 
problems!

If you are determined to do so you can make the objects persistent
using the approach I outline on my tutorial but adding a loop to cycle
over the contents of dir(). But you may find that recovering the
objects - especially if they have a mixed set of attribnutes - 
presents
even more problems...

IMHO This is a feature of python that should be considered unorthodox
and only to be used when no other approach will work!

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.alan-g.me.uk/




More information about the Tutor mailing list