[Tutor] General programming questions
w chun
wescpy at gmail.com
Thu Oct 27 12:49:26 CEST 2005
On 10/27/05, Matt Williams <matthew.williams at cancer.org.uk> wrote:
> At the moment, I have something like:
>
> def __init__ (self, a, b, c):
> if type(a) == type("a")
> then.....
> elif type(a) == type(["a"])
> then....
>
> I'm sure there must be a better way to do this (both the polymorphism
> and the type testing) - but I don't know how to do it.
i'd follow alan's advice with regards to the multiple subclasses and
using a factory object to evaluate and instantiate the appropriate
class instance.
as far as the code above, the 1st improvement is to change "type(a) ==
type(...)" to "type(a) is type(...)" since your evaluations will work
faster (because there is one less comparison to make -- the type
objects are all the same, so why also check their *values* are the
same too?); and finally, even faster is "isinstance(a, ...)".
hope this helps!
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2006,2001
http://corepython.com
wesley.j.chun :: wescpy-at-gmail.com
cyberweb.consulting : silicon valley, ca
http://cyberwebconsulting.com
More information about the Tutor
mailing list