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.


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()
    # 1

    counter = counter.get_new_instance()
    # 1

Subscribe to

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