polymorphism in python
Jay O'Connor
joconnor at cybermesa.com
Thu Nov 27 12:04:45 EST 2003
Roy Smith wrote:
>In article <mailman.1127.1069899957.702.python-list at python.org>,
> "Robert Brewer" <fumanchu at amor.org> wrote:
>
>
>
>>Roy Smith wrote:
>>
>>
>>>But how often is it actually useful to do such a thing? I can't
>>>remember the last time I wanted to do something like that in
>>>Python.
>>>
>>>
>>And Jay O'Connor replied:
>>
>>
>>>Generally, if you are programming to the interface and not to
>>>the class (which is what you are usually doing in OO programming,
>>>or should be if your language allows it) than testing for the
>>>actual type of an object is usually a no-no
>>>
>>>
>>I find this comes up quite often in application interfaces; that is,
>>points at which your code manipulates someone else's code in someone
>>else's language. A prime example is forming valid SQL statements:
>>
>>"SELECT * FROM xyz WHERE %(Name)s = %(Value)s" % ({'Name': fieldName,
>>'Value': fieldValue})
>>
>>
>
>OK, that's a fair example (and one that I've dealt with myself).
>
That was another example that came to mind...dealing with external
systems that care a bit more.
> In
>C++, you might write a polymorphic function:
>
>MyClass::doSqlStuff (String fieldName, int fieldValue);
>MyClass::doSqlStuff (String fieldName, String fieldValue);
>
>In Python you'd just write a single function and embed some logic to do
>the right thing depending on which type you got passed:
>
>def doSqlStuff (fieldName, fieldValue):
> if type (fieldValue) == StringType: # or whatever
> formatString = "'%s'"
> else:
> formatString = "%d"
>
>Either way, it's basicly "if this type, execute this code, if that type,
>execute some other code". The only real difference is that in something
>like C++, the conditional logic is done implicitly by the compiler (with
>hints from you in the form of which polymorphic methods you supply) and
>in Python you write the condition explicitly. I find the explicit form
>much easier to write, understand, and debug.
>
>
I actually ran into this recently with a Smalltalk application to
Postgresql. However, since Smalltalk allows you to add new behavior to
existing classes; I just added String>>asDBString and
Number>>asDBString. So my above code would look like:
MyClass>>doSqlStuff:: filedName with: fieldValue
formatString := fieldValue asDBString.
And it would polymophically get the right formatted string without any
type checking at all.
Adding such behavior to Object, Number, String, UndefniedObject etc...is
an effective way to get around such checking. For example if a value is
undefined (None) than you usually have to print something like "NULL"
(on INSERTs) to the database, so I implemented
UndefiinedObject>>asDBString to return 'NULL' so my code doensn't have
to check for nil values
More information about the Python-list
mailing list