A class method in Python is a method that is bound to the class, not to an individual object.

Class methods operate on class-level data (class variables) and are commonly used when a method needs to access or modify the state of the class as a whole.


What is a Class Method ?

Methods are functions that belong to a class. They define the behavior of objects created from the class.


Methods Accessing Class Properties :

In Python, methods can access object properties using the self parameter.

Python
class Person: def __init__(self, name, age): self.name = name self.age = age def get_info(self): return f"{self.name} is {self.age} years old" p1 = Person("Tobias", 28) print(p1.get_info()) #output Tobias is 28 years old


Methods Modifying Object Properties :

Python
class Person: def __init__(self, name, age): self.name = name self.age = age def celebrate_birthday(self): self.age += 1 print(f"Happy birthday! You are now {self.age}") p1 = Person("Linus", 25) p1.celebrate_birthday() p1.celebrate_birthday() #output Happy birthday! You are now 26 Happy birthday! You are now 27 


__str__( ) method :

The __str__( ) method is a special method that controls what is displayed when an object is printed.

Python
class Person: def __init__(self, name, age): self.name = name self.age = age def __str__(self): return f"{self.name} ({self.age})" p1 = Person("Tobias", 36) print(p1) #output Tobias (36) 

Deleting Methods from a Class :

Python allows you to delete a method from a class using the del keyword.

Python
class Person: def __init__(self, name): self.name = name def greet(self): print("Hello!") p1 = Person("Emil") del Person.greet p1.greet() # This will cause an error