polymorphism (was Re: Type checking in python?)
Greg Ewing
to_get_my_address at see.my.signature
Thu Jul 27 02:24:05 EDT 2000
Oivvio Polite wrote:
>
> What are your experiences? Does the type(arg) checking really become
> unmanageable as Paul's post implies? If so what are the alternative routes?
It's not so much that it becomes unmanageable, but that it
needlessly constrains what kind of objects your methods can
operate on.
Rather than checking for specific types, a more flexible way
is to test whether they support the operations you need to do
on them. For example,
class myclass:
def __init__(self, arg):
if hasattr(arg, "read"):
# It seems to be a file or a file-like object
...
else:
# Assume it's a string or something that can be converted
to one
filename = str(arg)
...
--
Greg Ewing, Computer Science Department,
University of Canterbury, New Zealand
To get my email address, please visit my web page:
http://www.cosc.canterbury.ac.nz/~greg
More information about the Python-list
mailing list