Question

In ruby you can do this:

class A
    def self.a
        'A.a'
    end
end

puts A.a #-> A.a

How can this be done in python. I need a method of a class to be called without it being called on an instance of the class. When I try to do this I get this error:

unbound method METHOD must be called with CLASS instance as first argument (got nothing instead)

This is what I tried:

class A
    def a():
       return 'A.a'

print A.a()
Was it helpful?

Solution

What you're looking for is the staticmethod decorator, which can be used to make methods that don't require a first implicit argument. It can be used like this:

class A(object):
    @staticmethod
    def a():
        return 'A.a'

On the other hand, if you wish to access the class (not the instance) from the method, you can use the classmethod decorator, which is used mostly the same way:

class A(object):
    @classmethod
    def a(cls):
        return '%s.a' % cls.__name__

Which can still be called without instanciating the object (A.a()).

OTHER TIPS

There are two ways to do this:

@staticmethod
def foo():     # No implicit parameter
    print 'foo'  


@classmethod
def foo(cls):   # Class as implicit paramter
    print cls

The difference is that a static method has no implicit parameters at all. A class method receives the class that it is called on in exactly the same way that a normal method receives the instance.

Which one you use depends on if you want the method to have access to the class or not.

Either one can be called without an instance.

You can also access the class object in a static method using __class__:

class A() :
    @staticmethod
    def a() :
        return '{}.a'.format( __class__.__name__ )

At least this works in Python 3.1

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top