How to get/set class attributes in Python

Dan Sommers me at privacy.net
Sun Jun 12 10:13:46 EDT 2005


On Sun, 12 Jun 2005 15:35:46 +0200,
Kalle Anke <skromta at gmail.com> wrote:

> In learning Python I've understood that I should write code in such a
> way that it can handle different data and this is fine with me. But
> what if I have a class where different attributes should only have
> values of a certain type and everything else is an error.

> For example, if I have an class that defines three attributes: first
> and last name plus email address. The only valid data types for the
> first two are strings and for the last an EmailAddress class.

> How should I handle this in Python?

> Should I use just don't care (but I'm going to send the data to a
> database so I need to ensure that the data is OK)? Should I use
> 'isinstance' and check manually? Or should I do something else?

One key phrase here is "duck typing":  if it walks like a duck, and
swims like a duck, and quacks like a duck, then it's a duck, or at least
you can assume it's a duck.  For example:

    def put_something( file_open_for_writing, something ):
        file_open_for_writing.write( str( something ) )

I don't care if file_open_for_writing is "really a file," as long it has
a "write" method that writes a string somewhere.

The other key phrase is "we're all adults here":  if I import sin from
the math module and pass it a unicode string, I get what I deserve.

In lower-level methods/functions, I usually just assume that parameters
are correct, and let the higher-level code catch any exceptions that
occur becuase it (the higher-level code) messed up and passed the wrong
kind of parameter.  For example, UI code *has* to check things that
users type, but once that happens, there's no need for my program to
recheck every parameter on every function call all the way down.  Either
everything works, or that same UI code catches and logs a TypeError or
ValueError or KeyError exception and asks the user what to do next.

Regards,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>



More information about the Python-list mailing list