static method feature

Diez B. Roggisch deets_noospaam at web.de
Tue Nov 25 12:16:15 EST 2003


Hi,

> do you know why python development team decided to forbid polymorphism
> for static methods ? As you can do it in another languages (Java,...) it
> could be very handy if you can create utility classes with static
> methods that could be differentiate from the number of parameters.
> 
> with no static methods, it is already possible in python :
> 
> class Assert:
>      def assertEquals(self,expected,actual):
>          ...
>      def assertEquals(self,msg,expected,actual):
>          ...

Have you tried to make this run? It gives me this:

Traceback (most recent call last):
  File "/tmp/test.py", line 19, in ?
    ass.assertEquals(1,2)
TypeError: assertEquals() takes exactly 4 arguments (3 given)

when trying to invoke the first method.

Its not possible to have polymorphic methods in python at all - but you can
do this:

class Foo:
   def bar(_, *args):
     if len(args) == 2:
        pass
     elif len(args) == 3:
        pass

This should also work with your static methods. Of course you can think of
more elaborated ways of dispatching, e.g. based on type(s) and so on. This
shall just give you the idea.

For keyword-args, you use **kwargs. And OTOH you can use similar syntax to
invoke a method with a list of args:

def baz(one, two, three):
   pass

args = [1, 2, 3]

baz(*args)

Regards,

Diez




More information about the Python-list mailing list