[Tutor] is it possible to call a setter property during classinstantiation?
ALAN GAULD
alan.gauld at btinternet.com
Sat Aug 14 11:08:30 CEST 2010
so we don't usually care too much about types. Are you sure you
>>really need all that type checking code?
...I included a type check for a string to make sure that a future programmer
(or myself) wouldn't try to pass in a list of lines after a text has been split.
Other code internal to the Question class depends on the fact that the
incoming data arrives in the form of a single string.
Does it really? If so that suggfgests it will call a method that is unique to
strings?
If so an exception will be thrown that you can catch. but if your methods don't
use
methods that are unique to strings could you generalise them to be applicable
to any sequence type - including a user defined class that looks like a string
but is not derived from string?
If the wrong data type is fed, then I have a custom exception that gets raised
>to specify the problem. I guess the program would just crash with a
>TypeError if a list of lines was fed rather than a string,
>Or you catch the error where the method really needs a string rather than trying
>
to predict the possibility in the init method. Of course this might mean many
duplicated try/except clauses which might mess yopur code up just aws much.
So its a trade off. LBYL v EAFP (try Google :-)
Is it better in such cases to just let the program die a natural death,
>Or catch the error where it occurs and take remedial action. Would converting
to a string work? (Usually not because almost anything in Python returns a
value from str() even if only a description of type!)
Is there a better way to approach these issues?
>If you know which methods might be missing it can be more effective to
check for their existence rather than checking for an explicit type. Thus
code can check for a "file like object" by testing that the subset of file
operations they need are present. This can often be combined with binding
the methods to local variables for a slight performance improvement:
def f(aFile):
try: # we need to use read and close methods of the input object
_read = aFile.read
_close = aFile.close
except AttributeError:
raise TypeError
data = _read()
process(data)
_close()
I'm not saying its never necessary to check types but its a lot less
necessary than in static languages, especially if you try to write functions
that can operate on the widest set of data types possible and guard
against missing operations rather than "incorrect" types.
HTH,
Alan G.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100814/2dce69ac/attachment-0001.html>
More information about the Tutor
mailing list