python - How to overload __init__ method based on argument type? -


let's have class has member called data list.

i want able initialize class with, example, filename (which contains data initialize list) or actual list.

what's technique doing this?

do check type looking @ __class__?

is there trick might missing?

i'm used c++ overloading argument type easy.

a neater way 'alternate constructors' use classmethods. instance:

>>> class mydata: ...     def __init__(self, data): ...         "initialize mydata sequence" ...         self.data = data ...      ...     @classmethod ...     def fromfilename(cls, filename): ...         "initialize mydata file" ...         data = open(filename).readlines() ...         return cls(data) ...      ...     @classmethod ...     def fromdict(cls, datadict): ...         "initialize mydata dict's items" ...         return cls(datadict.items()) ...  >>> mydata([1, 2, 3]).data [1, 2, 3] >>> mydata.fromfilename("/tmp/foobar").data ['foo\n', 'bar\n', 'baz\n'] >>> mydata.fromdict({"spam": "ham"}).data [('spam', 'ham')] 

the reason it's neater there no doubt type expected, , aren't forced guess @ caller intended datatype gave you. problem isinstance(x, basestring) there no way caller tell you, instance, though type not basestring, should treat string (and not sequence.) , perhaps caller use same type different purposes, single item, , sequence of items. being explicit takes doubt away , leads more robust , clearer code.


Comments

Popular posts from this blog

windows - Why does Vista not allow creation of shortcuts to "Programs" on a NonAdmin account? Not supposed to install apps from NonAdmin account? -

c++ - How do I get a multi line tooltip in MFC -

unit testing - How to mock PreferenceManager in Android? -