[Tutor] Dicts and classes
Lloyd Kvam
pythontutor@venix.com
Wed, 13 Mar 2002 08:36:02 -0500
Kirby's examples are wonderfully concise, but you might have overlooked the
setattr and getattr functions which are also possible solutions.
VanL wrote:
> Is there any way to do this:
>
> class customer:
> def __init__(self, info):
> for k in info.keys(): self.k = info[k]
Works if info is a dictionary.
(Again, see Kirby's examples for clever alternatives.)
> def change(self, name, value):
> self.name = value
setattr(self, name, value)
> def print(self, name):
> print self.name
print getattr(self, name)
>
> and even:
>
> bob = customer({'name':'Bob', 'lastname':'Jones','phone':'555-1234'})
> for member in bob.keys(): print bob.member
for member in bob.__dict__.keys(): print getattr(bob, member)
>
> or finally:
> print 'Customer: %(name)s %(lastname)s' % bob
print 'Customer: %(name)s %(lastname)s' % bob.__dict__
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice:
603-443-6155
fax:
801-459-9582