Python classmethod() built-in function

From the Python 3 documentation

Transform a method into a class method. A class method receives the class as an implicit first argument, just like an instance method receives the instance.

Examples

class Counter:
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1
        return self.count

    @classmethod  # passes the class as the first argument to the method instead of passing the instance
    def get_new_instance(cls):
        return cls()

if __name__ == "__main__":
    counter = Counter()
    print(counter.increment())
    # 1

    counter = counter.get_new_instance()
    print(counter.increment())
    # 1

Subscribe to pythoncheatsheet.org

Join 14,100+ Python developers in a two times a month and bullshit free publication , full of interesting, relevant links.