On Sat, 15 Sep 2007 02:45:10 -0700, James Stroud wrote: > Steven D'Aprano wrote: >> On Fri, 14 Sep 2007 18:19:45 -0700, James Stroud wrote: >> >>>> How do I subclass int and/or long so that my class also auto-converts >>>> only when needed? >>>> >>> Use __new__. >> >> The disadvantage of that is that your example code requires me to >> duplicate my methods in the long version and the int version. It's easy >> enough to work around that (class factory function) but it just seems >> all rather untidy... > > > The __new__ method is where you implement such decisions. There is no > "tidier" way for one class "auto-convert" to another class, which is > what you asked for (it says so right up there ^). So, if you don't like > the answer, don't ask the question.
How am I supposed to know if I will like the answer until I ask the question? If I knew the answer I wouldn't need to ask the question. Anyway, don't be so cranky and defensive. I was just pointing out that having to duplicate code between two different classes was untidy, not that __new__ is untidy. I thought that maybe I could inherit from both long and int, but Python doesn't like that: TypeError: Error when calling the metaclass bases multiple bases have instance lay-out conflict > The way to avoid duplicating methods (which is what you are asking for, > no?) while still allowing your classes to maintain their identities is > by using mixins: [snip code] I've never come to grips with mixins. It's probably high time I do. Thanks for the example. -- Steven. -- http://mail.python.org/mailman/listinfo/python-list