On Sat, Jul 16, 2011 at 5:53 AM, Inside <fancheyuj...@gmail.com> wrote: > def add(users): > assert(users, (tuple, list)) > #If necessary I'll also check every obj in the sequence to see whether > it's a User. > > I just follow some coding rules of me: > 1. Controlling "input" strictly. > 2. In a function keep doubting on its parameters until they're checked. > 3. Let potential errors raise as early as possible.
What you're doing there is writing code in Python, not writing Python code. To be more Pythonic, your code should actually stop caring about whether something is-a User, and instead simply care about whether or not it can be treated as a User. (And for Travaglia fans, yes, a User object WILL have an abuse() method.) Instead of asserting that the parameter is a User, just add it cheerfully to your list, and then when you iterate over the list and call some method on each one, you'll get an exception if one of them doesn't have that method. This allows a huge enhancement to polymorphism, in that you no longer need to worry about what your pointers are; in C++, you can run over a list of users and ask if they're all Students, but then you need to cast all those pointers if you're going to then ask them all what subjects they're studying. In Python, all you do is ask your list of objects what subjects they're studying - all the students will respond, and anything that doesn't know what "studying" is will throw an exception. The analogy with reality breaks down a bit here. I've seen plenty of students with no idea of what it means to study. But Python can handle that too - just 'del' the method in the subclass. ChrisA -- http://mail.python.org/mailman/listinfo/python-list