On Apr 10, 9:26 am, vsoler <vicente.so...@gmail.com> wrote:

> class Uno:
>     a=1
>     def m():
>         print "mouse"
>

...

> I cannot write
>       Uno.m()

By default (at least in Python 2.x), Python will pass any function
which is accessed through getattr on class or instance (usually called
a "method") an instance of the class as the first parameter.

You can avoid this by using the @staticmethod decorator in front:

class Uno:
    a = 1
    @staticmethod
    def m():
        print "mouse"

Then you can call Uno.m() directly.

This puts a "staticmethod" wrapper around m(), which explains to the
interpreter not to try to pass it the instance variable.

Also useful is @classmethod.

Interestingly, if you don't use staticmethod, the value in the class's
dictionary is an ordinary function, but if you do use staticmethod,
you no longer have a callable function in the class's dictionary:

>>> class fred:
...     def m():
...        print "foo"
...
>>> fred.__dict__['m']()
foo
>>> class fred:
...     @staticmethod
...     def m():
...        print "foo"
...
>>> fred.__dict__['m']()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'staticmethod' object is not callable


HTH,
Pat



Regards,
Pat
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to