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()
What you’re looking for is the
staticmethoddecorator, which can be used to make methods that don’t require a first implicit argument. It can be used like this:On the other hand, if you wish to access the class (not the instance) from the method, you can use the
classmethoddecorator, which is used mostly the same way:Which can still be called without instanciating the object (
A.a()).