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
Post a Comment