Skip to content

Latest commit

 

History

History
42 lines (34 loc) · 1.28 KB

File metadata and controls

42 lines (34 loc) · 1.28 KB
title Python classmethod() built-in function - Python Cheatsheet
description 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.
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