How to get/set class attributes in Python

Steven D'Aprano steve at REMOVETHIScyber.com.au
Sun Jun 12 12:40:42 EDT 2005


On Sun, 12 Jun 2005 15:35:46 +0200, Kalle Anke wrote:

> Anyway, I got another "problem" (read: being used to do it like this in other 
> languages). I'm used to use statically typed languages and for me one of the 
> advantages is that I can be sure that a parameter is of a certain type. So in 
> Java I could write
> 
> void doSomething( data : SomeClass ){ ... }
> 
> and I would be sure at compile time that I would only get SomeClass objects 
> as parameters into the method.
> 
> 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?

As you have worked out, Python doesn't do automatic type-checking for you.
But if you really do need type-checking, you can do it yourself with
isinstance() and/or type(). It isn't forbidden :-)

Or, you can try just coercing the data you have to the type you want. eg
instead of testing to see if obj is an integer, you might do:

try:
    obj = int(obj)
except:
    raise TypeError("can't convert to integer")
insert_in_database(obj)

This may be appropriate for your application.

Another method that is sometimes useful: you are expecting an instance of
Waterfowl class, but actually you are happy to use duck-typing: if it
looks like a duck, swims like a duck, and quacks like a duck, it is
close-enough to a duck:

def process_waterfowl(duck):
    """do things to an instance of Waterfowl, or equivalent"""
    try:
        look, swim, quack = duck.look, duck.swim, duck.quack
    except AttributeError:
        raise TypeError("object is not a waterfowl")
    # process any object that has look, swim and quack attributes
    # as if it were a waterfowl
    duck.look()
    duck.swim()
    duck.quack()


-- 
Steven.




More information about the Python-list mailing list