[C++-sig] Re: FW: Injected constructors

Ralf W. Grosse-Kunstleve rwgk at yahoo.com
Thu Jul 24 19:15:45 CEST 2003


--- Nicodemus <nicodemus at globalite.com.br> wrote:
> On a side note, this is a good reason to use classmethods in Python:
> 
> class ConfigurationLoader(object):
>     '''loads configuration from a filename or a file-like object.
>     '''
> 
>     def __init__(self, file_object):
>          self.file = file_object
> 
>     def FromFileName(cls, filename):
>          self = cls(file(filename))
>          return self
> 
>     FromFileName = classmethod(FromFileName)
> 
> 
> # usage
> config = ConfigurationLoader.FromFileName('test')
> 
> 
> This avoids having to do type checking in the __init__ method, plus it 
> makes the code a little more readable. 8)

FWIW: here is my preferred solution:

  def __init__(self, file_object=None, file_name=None):
    assert file_object is None or file_name is None
    assert file_object is not None or file_name is not None

Ralf


__________________________________
Do you Yahoo!?
Yahoo! SiteBuilder - Free, easy-to-use web site design software
http://sitebuilder.yahoo.com




More information about the Cplusplus-sig mailing list