Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python equivalent of a Ruby class method?

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()
like image 738
david4dev Avatar asked Nov 06 '10 09:11

david4dev


People also ask

What is Ruby class method?

Class Methods are the methods that are defined inside the class, public class methods can be accessed with the help of objects. The method is marked as private by default, when a method is defined outside of the class definition. By default, methods are marked as public which is defined in the class definition.

Does Ruby have class methods?

There are two standard approaches for defining class method in Ruby. The first one is the “def self. method” (let's call it Style #1), and the second one is the “class << self” (let's call it Style #2).


1 Answers

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.

like image 87
aaronasterling Avatar answered Oct 05 '22 08:10

aaronasterling