CodeSteps

Python, C, C++, C#, PowerShell, Android, Visual C++, Java ...

When to Use Class Methods and Static Methods in Python?

In Python, Class methods and Static methods are two types of methods that are NOT bound to instances in the same way as regular methods. They are defined using decorators and serve different purposes.

Class Methods (@classmethod)

A class method takes cls as its first parameter, which refers to the class itself (not the instance). It can access and modify class state that applies across all instances. Class methods are defined using the @classmethod decorator.

Static Methods (@staticmethod)

A Static method does not take self or cls as its first parameter. It behaves like a regular function but belongs to the class’s namespace. Used when some processing is related to the class but doesn’t need access to class or instance data. Static methods are defined using the @staticmethod decorator. These are also called utility functions.

Here is an example code contains both class & static methods.

# Color class
class Color:
	color = "Blue (Default)"

	def Set(self, color):
		self.color = color

	def Print(self):
		print("Class color is: ", Color.color, " - Instance color is: ", self.color)
	
	@classmethod
	def SetDefault(cls, color):
		cls.color = color
	
	@staticmethod
	def rgb(red, green, blue):
		return hex((red << 16) | (green << 8) | blue)

When you run the above code from Python prompt, the result looks like below:

>>> Color.color
'Blue (Default)'
>>> cl=Color()
>>> cl.color
'Blue (Default)'
>>> cl.Set("Green")
>>> cl.color
'Green'
>>> cl.Print()
Class color is:  Blue (Default) - Instance color is:  Green
>>> Color.color
'Blue (Default)'
>>> Color.rgb(0, 255, 255)
'0xffff'

/Shijit/

When to Use Class Methods and Static Methods in Python?

Leave a Reply

Your email address will not be published. Required fields are marked *

Scroll to top