Need help with Python class idioms
Josiah Carlson
jcarlson at uci.edu
Wed Jan 21 16:12:04 EST 2004
On 21 Jan 2004 12:43:28 -0800
tad at tadland.net (Tad Marko) wrote:
> Howdy!
>
> I'm trying to get my head around Python and I've come to realize that
> there are a lot of idioms in Python that are a bit different than in
> other languages. I have a class similar to what I've included below.
> The only difference is that in the real class, I have even more
> mandatory attributes. Too many to specify at once on a constructor and
> they don't always exist at construction time anyway, so the accessor
> idiom must remain.
>
> Can anyone suggest a more Pythony way to do the following?
>
> Thanks,
> Tad
>
> #!/bin/env python
>
> class A:
> def __init__(self):
> self.mandatoryVar1 = None
> self.mandatoryVar2 = None
>
> def setMV1(self, mv1):
> self.mandatoryVar1 = mv1
>
> def setMV2(self, mv2):
> self.mandatoryVar2 = mv2
>
> def saveToDB(self, db):
> if self.mandatoryVar1 == None:
> raise Exception, "Mandatory Var 1 not set."
> if self.mandatoryVar2 == None:
> raise Exception, "Mandatory Var 2 not set."
>
> # Using db, do whatever saving stuff is needed.
mandatoryvariables = dict(mandatoryvar1=mv1, mandatoryvar2=mv2...)
inst = A()
inst.__dict__.update(mandatoryvariables)
That should work for you.
- Josiah
More information about the Python-list
mailing list