Need help with Python class idioms

James Henderson james at logicalprogression.net
Wed Jan 21 15:51:50 EST 2004


On Wednesday 21 January 2004 8:43 pm, 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.

What about this:

class A:
    def __init__(self, mandatoryVar1, mandatoryVar2):
        self.mandatoryVar1 = mandatoryVar1
        self.mandatoryVar2 = mandatoryVar2

-- 
James Henderson, Logical Progression Ltd.
http://www.logicalprogression.net/
http://sourceforge.net/projects/mailmanager/





More information about the Python-list mailing list