beginner question: extending python types

Fernando PĂ©rez fperez528 at yahoo.com
Mon May 13 20:58:56 EDT 2002


Uwe Mayer wrote:

> Hi,
> 
> I am totally new to python and was about to start programming when more
> and more questions upon "how to do it actually" came up.
> 
> My problem: I want do write classes which behave like algebraic
> structures, i.e. a group, a field or vector space and then want to work
> on them.
> 
> To my first question:
> I know I can overwrite built-in operations like add with, f.e. __add__()
> methods, but can I add new f.e. postfix operators like "!" (facculty: n!
> = 1*2*3*4*...*n)?`

You can't add new operators to python, you can only override existing ones. 
But you can perhaps make do with methods:

class myint(int):
 def fac(self):
   ## compute factorial

print myint(5).fac() # <==> 5!

Kludgy, I know.


> 
> My second question:
> I found Python lacking the type of a "set". i.e. an unordered list. I'd
> just wanted to use a normal list and pretend there was no order. Of
> course I want to iterate over them and in section 2.2.5 of the Python
> Library Reference they say that the method __iter__() must return an
> iterator object. I couldn't find a class called iterator in the Library
> and Language Reference...

For a start, you can use a dict and have your elements be keys with some 
trivial value. Repeated elements don't add to the set because each unique key 
only exists once. You can then create syntactic sugar to make it look more 
like a set, and implement further set operations. 

> 
> To my last question for now:
> I want to force certain parameters of methods to be of a specific type,
> so that when I expect a set I'll get a set or a sub-class thereoff. How
> to I controll that? Use the type() function and raise an IllegalType
> exception otherwise?

To elaborate on Alex's response: abandon python if you insist on using types, 
but you can still use python for this problem. It's just that you'll be 
better off learning a different way of achieving your goals which is not 
based on strict type checking.

Cheers,

f.



More information about the Python-list mailing list