Class method

Class Method

A class method is a function that is associated with the class rather than an instance of the class. It can be called on the class itself, rather than on an instance of the class. Class methods are often used to create factory methods, which are methods that create and return instances of the class.

In Python, a class method is defined using the @classmethod decorator. The first argument to a class method is conventionally named cls, and refers to the class itself.


class MyClass:
    @classmethod
    def my_class_method(cls):
        print(f"This is a class method of {cls.__name__}")

MyClass.my_class_method()  # Output: "This is a class method of MyClass"

In Java, a class method is defined using the static keyword. A static method is associated with the class rather than an instance of the class, and can be called on the class itself.


public class MyClass {
    public static void myClassMethod() {
        System.out.println("This is a class method of MyClass");
    }
}

MyClass.myClassMethod();  // Output: "This is a class method of MyClass"

In Ruby, a class method is defined using the self. prefix. The first argument to a class method is conventionally named self, and refers to the class itself.


class MyClass
    def self.my_class_method
        puts "This is a class method of MyClass"
    end
end

MyClass.my_class_method  # Output: "This is a class method of MyClass"

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe