On Mar 17, 4:31 pm, Paulo da Silva <[EMAIL PROTECTED]> wrote: > Sorry to put here too many questions about __init__ __new__ > stuff but I always found a new problem when using them. > I have searched for simple __new__ docs on how to do the > basic things but find none. > > After trying the solutions people gently posted here > (thanks) I run into new trouble when I go with further > development. > > Here is the new situation. > > As suggested in a previous post, I used __new__ to > subclass date class but now cPickle/pickle loads > does not work. > > from datetime import date > import cPickle,string > > class MyDate(date): > def __new__(cls,year,month=None,day=None): > if type(year) is str: > year,month,day=map(int,string.split(year,'-')) > if year<100: > year+=2000 > return date.__new__(cls,year,month,day) > > class C1(object): > def __init__(self): > self.x=MyDate("2007-3-15") > > def f(self): > print self.x > > c1=C1() > > d=cPickle.dumps(c1) > c2=cPickle.loads(d) > c2.f() > > 1. year is passed to __new__ as a string but with invalid > contents! > > 2. If I had a __new__ in class C1, cPickle.loads invokes it > with only one parameter. This forces to allow __new__ accept > only 1 parameter (cls) which I don't want for the normal > situation. > > Thanks for your patience. > Paulo
Any special reason you have to use __new__ for this factory method? This version works, without the problems with __new__: def getDate(*args): if isinstance(args[0],basestring): year,month,day = map(int,string.split(args[0],'-')) else: year,month,day = args if year < 100: year += 2000 return date(year,month,day) class C1(object): def __init__(self): #self.x=MyDate("2007-3-15") self.x = getDate("2007-3-15") def f(self): print self.x -- Paul -- http://mail.python.org/mailman/listinfo/python-list