More __init__ methods

Larry Bates larry.bates at vitalEsafe.com
Thu Nov 6 15:41:39 EST 2008


Mr.SpOOn wrote:
> On Thu, Nov 6, 2008 at 7:44 PM, Tim Golden <mail at timgolden.me.uk> wrote:
>> While that's no bad thing, you don't really need to do
>> that simply to understand these examples: they're just
>> saying "do whatever you need to to make these method
>> class methods, not instance methods".
> 
> Yes.
> 
> I think this changes the design of my class.
> 
> I mean, till now I had something like:
> 
> class foo:
>     def __init__(self, string=None, integer=None, someinstance=None):
>          self.a = 0
>          self.b = 0
> 
>          if string:
>             # do something to calculate "a and b"
>          elif integer:
>             # do something else to calculate "a and b"
>          ...
>          ...
> 
> So I used different methods to calculate the same variables.
> 
> Now I must pass a and b to the main constructor and calculate them in
> the classmethods.
> 
> class foo:
>     def __init__(self, a, b):
>          self.a = a
>          self.b = b
> 
>     @classmethod
>     def from_string(self, ..):
>           ...
>           ...
> 
> What I mean is: I can't use anymore __init__ as the default
> constructor, but I always have to specify the way I'm creating my
> object. Am I right? I'm asking just to be sure I have understood.

Is there some reason not to use something like the following?

class foo:
     def __init__(self, val):
         self.a = 0
         self.b = 0

         if isinstance(val, basestring):
             #
             # do something to calculate "a and b"
             #

         elif isintance(val, int):
             #
             # do something else to calculate "a and b"
             #

         elif isinstance(val, someinstance)
             #
             # do something else to calculate "a and b"
             #

         else:
             #
             # Don't know what to do with unknown type
             #
             raise ValueError()



-Larry



More information about the Python-list mailing list